LeetCode-Rotate Image

Posted by mapoto4 on 2017-08-03

问题

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

解题思路

此题是将一个二维正方矩阵数组旋转90度。
如下变换所示,最外层数组旋转方式。

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

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
public void rotate(int[][] matrix) {
int n = matrix.length;
int temp = 0;
for (int i = 0; i <= (n - 1) / 2; i++) {
for (int j = i; j < n - 1 - i; j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
matrix[j][n - 1 - i] = temp;
}
}
}