[LeetCode]—Rotate Image 矩阵90度翻转
Rotate Image
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?
分析:如果手动模拟,将依次从外向内移动4条边,比较复杂。
可以考虑将90度翻转,转换为矩阵对角线、水平、垂直对称问题。90度翻转有如下转换关系:
有了90度的对称旋转方法,180度与 270度都可以通过多次90度旋转解决,但同样也可以直接研究其旋转关系。
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Solution{
public:
void rotate(vector<vector<int> > &matrix){
int n=matrix.size();
if(n==1)return;
//以副对角线为轴翻转。
int i,j;
for(i=0;i<n;i++){
for(j=n-1-i;j>=0;j--){
if((n-1-i)==j)continue; //对角线上的点不用翻转
swap(matrix[i][j],matrix[n-1-j][n-1-i]);
}
}
//以水平中轴线为轴线翻转。
int bott=n-1;
i=0;
while(i<bott){
for(j=0;j<n;j++){
swap(matrix[i][j],matrix[bott][j]);
}
i++;
bott--;
}
return;
}
};