Fork me on GitHub

leetcode——[048]Rotate Image旋转图像

题目

给定一个 n × n 的二维矩阵表示一个图像。

将图像顺时针旋转 90 度。

说明:

你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。

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

Rotate the image by 90 degrees (clockwise).

Note:

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
给定 matrix = 
[
[1,2,3],
[4,5,6],
[7,8,9]
],

原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

示例 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
给定 matrix =
[
[ 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]
]

解题方法

拆分为翻折

将矩阵顺时针旋转90°,分解为绕轴翻转的步骤。也就是先绕对角线翻转,然后绕两腰中位线翻转。要求直接操作原矩阵,所以不能直接使用新矩阵来保存结果,使用一个变量来保存被替换的单元。这段代码跑了2ms,超过93.40%的java提交。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
// Method_01 2ms 93.40%
public void rotate(int[][] matrix) {
int tmp;
int length = matrix.length;
// fold along the diagonal
for (int i = 0; i < length; i++) {
for (int j = 0; j < length - i; j++) {
tmp = matrix[length - j - 1][length - i - 1];
matrix[length - j - 1][length - i - 1] = matrix[i][j];
matrix[i][j] = tmp;
}
}
// fold along the median line
for (int i = 0; i < length / 2; i++) {
for (int j = 0; j < length; j++) {
tmp = matrix[length - i - 1][j];
matrix[length - i - 1][j] = matrix[i][j];
matrix[i][j] = tmp;
}
}
}
}

旋转对应坐标变换

顺时针旋转90°,对应360°/90°=4个单元进行逐一替换,对应单元的坐标替换关系为:

[i, j] -> [j, matrix.length - 1 - i];

[j, matrix.length - 1 - i] -> [matrix.length - 1- i, matrix.length - 1 - j];

[matrix.length - 1- i, matrix.length - 1 - j] -> [matrix.length - 1- j, i];

[matrix.length - 1- j, i] -> [i, j]。

按这种坐标转换,遍历矩阵的四分之一即可。这段代码也跑了2ms,超过了93.40%的java提交。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
// Method_02 2ms 93.40%
public void rotate(int[][] matrix) {
int tmp;
int length = matrix.length;
for (int i = 0; i < length / 2; i++) {
for (int j = 0; j < (length + 1) / 2; j++) {
tmp = matrix[i][j];
int i1 = j;
int j1 = matrix.length - 1 - i;
int i2 = j1;
int j2 = matrix.length - 1 - j;
int i3 = j2;
int j3 = i;
matrix[i][j] = matrix[i3][j3];
matrix[i3][j3] = matrix[i2][j2];
matrix[i2][j2] = matrix[i1][j1];
matrix[i1][j1] = tmp;
}
}
}
}

结语

Keep coding!

BJTU-HXS wechat
海内存知己,天涯若比邻。