leetcode之图像旋转(Rotate Image)
1.新建一个数组,将原数组的数据按规律复制到新数组,这种方法做不到in-place,占用了额外一个数组的空间
newx = y;
newy = n-1-x;
2.我们可以按ring by ring的顺序进行操作
交换在每个ring上的4个点之间进行
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for(int x = 0; x <= (n - 1) >> 1; x++) {
for(int y = x; y <= n - 2 - x; y++) {
int newx1 = y;
int newy1 = n - 1 - x;
int newx2 = newy1;
int newy2 = n - 1 - newx1;
int newx3 = newy2;
int newy3 = n - 1 - newx2;
int temp = matrix[newx1][newy1];
matrix[newx1][newy1] = matrix[x][y];
matrix[x][y] = matrix[newx3][newy3];
matrix[newx3][newy3] = matrix[newx2][newy2];
matrix[newx2][newy2] = temp;
}
}
}
}
3.将上下的行进行反转,然后按主对角线进行对称交换;这这种方法也很容易做到逆时针旋转。
/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3
*/
/*
* anticlockwise rotate
* first reverse left to right, then swap the symmetry
* 1 2 3 3 2 1 3 6 9
* 4 5 6 => 6 5 4 => 2 5 8
* 7 8 9 9 8 7 1 4 7
*/