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?
本地使得二维矩阵,旋转90角度。
通过实际数据分析,通过两个步骤的元素交换可实现目标:
按照主对角线,将对称元素交换
按照列,将对称列元素全部交换
即可达到,使得二维矩阵,本地旋转90个角度。
public void rotate(int[][] matrix) {
if (matrix.length == 0)
return;
int n = matrix.length;
//主对角线元素交换
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
//对称列元素交换
for (int i = 0, j = n - 1; i < j; i++, j--)
for (int k = 0; k < n; k++) {
int temp = matrix[k][i];
matrix[k][i] = matrix[k][j];
matrix[k][j] = temp;
}
}