题目:
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?
解答:
一开始想的很复杂,希望找到一个通式应对所有角度的旋转。所有的细节写在《【图像处理】基于OpenCV底层实现的图片旋转》。
其实没有必要,因为90度是非常特殊的一种旋转,可以直观上赋值:
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<int> tmp(m, 0);
vector<vector<int>> ans(n, tmp);
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
{
ans[j][m-1 - i] = matrix[i][j];
}
matrix = ans;
return;
}
};
但仔细看题目要求:in-place(原地)。想了半天没想出来原地旋转的方法。直到看到巧妙做法:传送门。精粹就在下图中:
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
int i,j,temp;
int n=matrix.size();
// 沿着副对角线反转
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n - i; ++j) {
temp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][n - 1 - i];
matrix[n - 1 - j][n - 1 - i] = temp;
}
}
// 沿着水平中线反转
for (int i = 0; i < n / 2; ++i){
for (int j = 0; j < n; ++j) {
temp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - i][j];
matrix[n - 1 - i][j] = temp;
}
}
}
};