简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM