'Rotate 2D Array Clockwise

  // pre: m is a square 2-D array (m.length == m[0].length)
 // post: rotates the array 90 degrees to the right
// When the user presses "F1" on the keyboard, this method will run.
public static void rotateRight(Object[][] m) {
  for (int row = 0; row < m[0].length; row++){
    for (int col = row; col < m.length; col++){
     Object temp = m[row][col];
     m[row][col] = m[col][row];
     m[col][row] = temp;
  }
 }
}

Why does my code not rotate? It seems that it is only transposing the rows although its supposed to rotate



Solution 1:[1]

You are probably looking for something like this:

static int[][] rotateRight(int[][] mat) {
    final int M = mat.length;
    final int N = mat[0].length;
    int[][] ret = new int[N][M];
    for (int r = 0; r < M; r++) {
        for (int c = 0; c < N; c++) {
            ret[c][M-1-r] = mat[r][c];
        }
    }
    return ret;
}

As for the reason why your code is transposing and not rotating is because you set m[row][col] = m[col][row]. Doing this for all the elements only transposes the array, and has nothing to do with rotating.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jhanzaib Humayun