題目
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
這題就是想清楚移動時索引值得變化關系即可。還要注意一輪移動涉及四個元素,因此只要遍歷四分之一的矩陣即可。
代碼
public class RotateImage {
public void rotate(int[][] matrix) {
int N = matrix.length;
for (int i = 0; i < N / 2; ++i) {
for (int j = i; j < N - 1 - i; ++j) {
int temp = matrix[i][j];
matrix[i][j] = matrix[N - 1 - j][i];
matrix[N - 1 - j][i] = matrix[N - 1 - i][N - 1 - j];
matrix[N - 1 - i][N - 1 - j] = matrix[j][N - 1 - i];
matrix[j][N - 1 - i] = temp;
}
}
}
}