题解
这题只要有点分解的意识就好了。旋转矩阵其实就是在按照顺时针
顺序依次swap一行/列,如下图。每完成一个 口字再往内部走就是个
更小的 口字。
4
- - - |
3 | | 1
| |
| - - -
2
Code
class Solution {
public:
int cot[500];
void rotate(vector<vector<int>>& matrix) {
if(matrix.empty()) return;
int len = matrix.size()-1; // 边长
int t,x,y,tmp;
x=y=0;
while(len>=1){
t=0;
for(int j=y;j<y+len;j++)
cot[t++]=matrix[x][j];
y+=len;t=0; // x=0, y=len
for(int i=x;i<x+len;i++){
tmp = matrix[i][y];
matrix[i][y]=cot[t];
cot[t++]=tmp;
}
x+=len;t=0;// x=len, y=len
for(int j=y;j>y-len;j--){
tmp = matrix[x][j];
matrix[x][j]=cot[t];
cot[t++]=tmp;
}
y-=len;t=0;// x=len, y=0
for(int i=x;i>x-len;i--){
tmp = matrix[i][y];
matrix[i][y]=cot[t];
cot[t++]=tmp;
}
x-=len;t=0;// x=0, y=0
for(int j=y;j<y+len;j++){
tmp = matrix[x][j];
matrix[x][j]=cot[t];
cot[t++]=tmp;
}
x++;y++;
len-=2;
}
}
};