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 void rotate(int[][] matrix) {
if (matrix == null) {
return;
}
int num = matrix[0].length;
if (num == 0) {
return;
}
for (int n = 0; n < num / 2; n++) {
int count = num - n * 2;
for (int i = 0; i < count - 1; i++) {
//top
int r = 0;
int c = i;
int pre = matrix[n + r][n + c];
matrix[n + r][n + c] = matrix[n + count - c - 1][n + r];
//right
r = i;
c = count - 1;
int temp = matrix[n + r][n + c];
matrix[n + r][n + c] = pre;
pre = temp;
//bottom
r = count - 1;
c = count - i - 1;
temp = matrix[n + r][n + c];
matrix[n + r][n + c] = pre;
pre = temp;
//left
r = count - 1 - i;
c = 0;
temp = matrix[n + r][n + c];
matrix[n + r][n + c] = pre;
pre = temp;
}
}
}