# LeetCode：48.旋转图像

``````示例 1:

[
[1,2,3],
[4,5,6],
[7,8,9]
],

[
[7,4,1],
[8,5,2],
[9,6,3]
]

[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],

[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]``````

[0][0] –> [0][2]

[0][2] –> [2][2]
[2][2] –> [2][0]
[2][0] –> [0][0]
[0][1] –> [1][1]
[1][1] –> [2][1]
[2][1] –> [1][0]
[1][0] –> [0][1]

4 的二维数组。
[0][0] –> [0][3]
[0][3] –> [3][3]
[3][3] –> [3][0]
[3][0] –> [0][0]
[0][1] –> [1][3]
[0][2] –> [2][3]
[1][1] –> [1][2]

``[x][y] --> [y][n - 1 - x]``

a = a ^ b
b = a ^ b
a = a ^ b

[0][0] –> [0][3]
[0][3] –> [3][3]
[3][3] –> [3][0]
[3][0] –> [0][0]

``[x][y] --> [y][n - 1 - x]``

``[x][y] --> [n - 1 - y][x]``

`````` for (int j = 0; j < 3; j++) {
x2 = n - 1 - y1;
y2 = x1;

matrix[x1][y1] = matrix[x1][y1] ^ matrix[x2][y2];
matrix[x2][y2] = matrix[x1][y1] ^ matrix[x2][y2];
matrix[x1][y1] = matrix[x1][y1] ^ matrix[x2][y2];

x1 = x2;
y1 = y2;
}``````

3 3 的矩阵，有9个元素，需要旋转2组元素。
4
4 的矩阵，有16个元素，需要旋转4组元素。

``int count = n * n / 4;``

3 3 的矩阵，需要旋转2组元素，需要定位到 [0][0], [0][1]
4
4 的矩阵，需要旋转4组元素，需要定位到 [0][0], [0][1], [0][2], [1][1]
5 * 5 的矩阵，需要旋转6组元素，需要定位到 [0][0], [0][1], [0][2], [0][3], [1][1], [1][2]

``````public void rotate(int[][] matrix) {
int n = matrix.length;

if (n <= 1) {
return;
}

//旋转次数
int count = n * n / 4;

int x = 0;
int y = 0;
int z = 0;

int x1, y1, x2, y2;

for (int i = 0; i < count; i++) {
if (z >= (n - 1) - 2 * x) {
x += 1;
z = 0;
}
y = z + x;
z += 1;

x1 = x;
y1 = y;

for (int j = 0; j < 3; j++) {
x2 = n - 1 - y1;
y2 = x1;

matrix[x1][y1] = matrix[x1][y1] ^ matrix[x2][y2];
matrix[x2][y2] = matrix[x1][y1] ^ matrix[x2][y2];
matrix[x1][y1] = matrix[x1][y1] ^ matrix[x2][y2];

x1 = x2;
y1 = y2;
}
}
}``````