LeetCode Q48 Rotate Image

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public void rotate(int[][] matrix) {
//以对角线为轴交换
for (int i = 0; i < matrix.length; i++)
{
//j <= i 确保交换除了【0,0】,【1,1】和 【2,2】位置的数
for (int j = 0; j <=i; j++)
{
if (i == j) {
continue;
}

int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
//交换column
//左半边的值是i,右半边的值是j
//j从最右边开始,与最左边的竖着交换,j往左递减
for (int i = 0, j = matrix.length - 1; i < matrix.length / 2; i++, j--)
{
for (int k = 0; k < matrix.length; k++) {
int temp = matrix[k][i];
matrix[k][i] = matrix[k][j];
matrix[k][j] = temp;
}
}

}