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?
给你一个n*n的二维矩阵,顺时针旋转90°,不申请额外的空间.
先关于主对角线对称,再左右对称.
public class A048RotateImage {
public void rotate(int[][] matrix) {
int n = matrix.length;
// 转置(关于主对角线对称)
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// 左右对称
for(int i = 0; i < n; i++) {
for(int j = 0; j < n / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n - j - 1];
matrix[i][n - j - 1] = temp;
}
}
}
}