Description
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
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]
]
Analyse
题意简洁明了,让你对一个图像(2*2矩阵)做绕中心顺时针旋转90°操作,要求不使用额外的矩阵存储,只需要在原图像更改。
其实也就是数字图像处理图像旋转那一块的东西,只需要把图像中心移到(0,0),然后进行旋转就好,我觉得这里主要的问题就是行列坐标与x,y坐标的一个对应关系,以及不使用额外的矩阵。由于旋转的是90°,那我们可以将矩阵划分为1/4,我们只需要交换对应四个位置的数的顺序即可,这样我们就不需要使用额外的矩阵了,这1/4一定要切好,要保证每个数字都只旋转了一次。在平移之后,进行转换,转换方式为(x,y)->(y,-x),然后再平移回去即可。
方框框出的就是旋转区域。
Code
class Solution {
public:
void rotate(vector<vector<int> >& matrix) {
int n = matrix.size(), l, r;
float d = float(n - 1) / 2;
l = n / 2 + n % 2;
r = n / 2;
for (int i = 0; i < l; i++) {
for (int j = 0; j < r; j++) {
int x0 = i, y0 = j, x1, y1;
int temp1, temp2 = matrix[x0][y0];
for (int k = 0; k < 4; k++) {
float tempx = float(x0) - d, tempy = float(y0) - d;
x1 = int(tempy + d); y1 = int(-tempx + d);
temp1 = matrix[x1][y1];
matrix[x1][y1] = temp2;
temp2 = temp1;
x0 = x1;y0 = y1;
}
}
}
return;
}
};