48. Rotate Image
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 == null)
return;
int n = matrix.length;
// 沿着副对角线旋转
for (int i = 0; i < n; i++)
for (int j = 0; j < n - i; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][n - 1 - i];
matrix[n - 1 - j][n - 1 - i] = temp;
}
// 沿着中间水平线旋转
for (int i = 0; i < n / 2; i++)
for (int j = 0; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - i][j];
matrix[n - 1 - i][j] = temp;
}
}
纯模拟,从外到内一圈一圈的转,但这个方法太慢。
A[i][j] -> A[j][n-1-i] -> A[n-1-i][n-1-j] -> A[n-1-j][i] -> A[i][j]
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int layer = 0; layer < n / 2; layer++) {
int start = layer;
int end = n - 1 - start;
for (int i = start; i < end; i++) {
int offset = i - start;
int temp = matrix[start][i];
// left to top;
matrix[start][i] = matrix[end - offset][start];
// bottom to left;
matrix[end - offset][start] = matrix[end][end - offset];
// right to bottm;
matrix[end][end - offset] = matrix[i][end];
// top to right;
matrix[i][end] = temp;
}
}
}
参考:
https://yq.aliyun.com/articles/3878
https://segmentfault.com/a/1190000007429004