題目
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]
]
分析
旋轉(zhuǎn)的時(shí)候绵脯,元素的交換只發(fā)生在所有相距45度的4個(gè)元素之間。而這些包含4個(gè)元素的小組继效,可以按照矩陣的層次由內(nèi)而外分成[0, (n+1)./2)層眨层,而每一層中包含4[0, n-2i-1)個(gè)元素。這樣遍歷每一組失受,然后交換每一組中的元素即可讶泰。
實(shí)現(xiàn)
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n=matrix.size();
for(int i=0; i<(n+1)/2; i++){
for(int j=0; j<n-2*i-1; j++){
int x1=i, y1=i+j;
int x2=i+j, y2=n-1-i;
int x3=n-1-i, y3=n-1-(i+j);
int x4=n-1-(i+j), y4=i;
int tmp = matrix[x4][y4];
matrix[x4][y4] = matrix[x3][y3];
matrix[x3][y3] = matrix[x2][y2];
matrix[x2][y2] = matrix[x1][y1];
matrix[x1][y1] = tmp;
}
}
}
};
思考
我這種方法應(yīng)該是比較直接的咏瑟。另外取巧的方法還有,將轉(zhuǎn)置分成兩步完成:首先沿副對(duì)角線翻轉(zhuǎn)痪署,再沿水平中心線翻轉(zhuǎn)即可码泞。或者先沿水平中線翻轉(zhuǎn)狼犯,再沿主對(duì)角線翻轉(zhuǎn)余寥。