LeetCode解题 48:Rotate Image
Problem 48: Rotate Image [Medium]
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.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
来源:LeetCode
解题思路
将数组看作一个由N/2个正方形圈组成的套圈,每一次循环都将一个圈在原地顺时针旋转90°,能够保证不会重复旋转,并且不需要额外数组空间。
如下图所示:
一次旋转圈1:
第二次旋转圈2:
具体过程:
- 循环N/2次,每次旋转的正方形的四个顶点为:
t o p _ l e f t = [ s i d e , s i d e ] , top\_left = [side, side], top_left=[side,side],
t o p _ r i g h t = [ s i d e , N − s i d e − 1 ] , top\_right = [side, N-side-1], top_right=[side,N−side−1],
b o t t o m _ r i g h t = [ N − s i d e − 1 , N − s i d e − 1 ] , bottom\_right = [N-side-1, N-side-1], bottom_right=[N−side−1,N−side−1],
b o t t o m _ l e f t = [ N − s i d e − 1 , s i d e ] bottom\_left = [N-side-1, side] bottom_left=[N−side−1,side] - 旋转正方形时需要调换
4
∗
(
N
−
2
∗
s
i
d
e
−
1
)
4*(N-2*side-1)
4∗(N−2∗side−1)个点的位置。每四个点为一组,内部进行旋转替换,循环该过程
(
N
−
2
∗
s
i
d
e
−
1
)
(N-2*side-1)
(N−2∗side−1)次。
分组如图所示:
运行结果:
Solution (Java)
class Solution {
public void rotate(int[][] matrix) {
int N = matrix.length;
if(N == 0 || N == 1) return;
for(int i = 0; i < N / 2; i++){
rotate_sides(matrix, i, N);
}
}
private void rotate_sides(int[][] matrix, int side, int N){
for(int i = side; i < N - side - 1; i++){
int top = matrix[side][i];
int right = matrix[i][N-side-1];
int bottom = matrix[N-side-1][N-i-1];
int left = matrix[N-i-1][side];
matrix[i][N-side-1] = top;
matrix[N-side-1][N-i-1] = right;
matrix[N-i-1][side] = bottom;
matrix[side][i] = left;
}
}
}