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

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

思路

如果新开一个n*n的数组来存旋转后的结果,需要的空间就很多了。

因此题目要求我们in-place来进行操作。思路实际上很简单,依次交换左上角,右上角,右下角,左下角的像素点就可以实现旋转了。这道题目CC150这本书的第一章就出现了,也可以以此为参考。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
int start = 0;
int end = n - 1;
for(int j = n; j > 1; j = j-2){
for(int i = 0; i < end - start; i++){
//Upper-Right to TMP
int tmp = matrix[start+i][end];
//Upper-Left to Upper-Right
matrix[start+i][end] = matrix[start][start+i];
//Down-Left to Upper-Left
matrix[start][start+i] = matrix[end-i][start];
//Down-Right to Down-Left
matrix[end-i][start] = matrix[end][end-i];
//TMP to Down-Left
matrix[end][end-i] = tmp;
}
start++;
end--;
}
}
};