You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
给出一个图像(二维数组),做旋转变换(in place)
in place也就是不能另外分配一个数组,要在原数组上进行变换
思路:
顺时针旋转90度即为第一行变最后一列…
意味着要同时做行列的交换,需要记录的数字有点多。
拆分一下,只做行,列,对角线的交换,就会简单很多。
先做对角线的交换,把行换到列,然后再做列交换。
旋转变换分两步,第一步对角线翻转,第二步列中点处为中心轴左右翻转
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length == 0) {
return;
}
int n = matrix.length;
//先按对角线翻转
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
//swap
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
//按中心轴左右翻转
for(int i = 0; i < n; i++) {
for(int j = 0; j < n/2; j++) {
//swap
int tmp = matrix[i][j];
matrix[i][j] = matrix[i][n - 1 - j];
matrix[i][n - 1 - j] = tmp;
}
}
}