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?
Subscribe to see which companies asked this question
这道题的关键是找到转换前后数组中不同位置元素的映射关系。
在纸上可以模拟转换过程,容易求得:
x' = n - y ;
y' = x.
(x,y)为转换前的数组下标,(x',y')为转换后的数组下标。转换过程中(x,y)中的数字将覆盖到(x',y'),(x',y')中的数字也通过上面的映射规则覆盖到下一个(x‘',y'');
这样映射四次将回到(x,y)。
下面是该思路的JAVA实现,要注意前两层循环的上下界,这个地方比较容易弄错。
public class Solution {
public void rotate(int[][] matrix) {
for(int i = 0; i < matrix.length /2 ; i ++){
for(int j = i ; j < matrix.length -1 -i ; j ++){
int last = matrix[i][j];
int i1 = i;
int j1 = j;
for(int k = 0 ; k < 3 ; k ++){
matrix[i1][j1] = matrix[matrix.length -1 -j1][i1];
int tmp = j1;
j1 = i1;
i1 = matrix.length -1 -tmp;
}
matrix[i1][j1] = last;
}
}
}
}