记录一下,觉得倒水思想来做 总体看起来还是比较清晰的。
bash
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int a[4][2] = {{0,1}, {1,0}, {0,-1},{-1,0}};
int direction=0; //方向
int num=0;
int S =n*n;
int x = 0;
int y = 0;
vector<vector<int>> Matrix(n, vector<int>(n, 0));
while(num!=S){
num++;
Matrix[x][y]=num;
x+=a[direction][0];
y+=a[direction][1];
if(x>=n || y>=n || x<0 || y<0 || Matrix[x][y]!=0){
x-=a[direction][0];
y-=a[direction][1];
direction = (direction+1)%4;
x+=a[direction][0];
y+=a[direction][1];
}
}
return Matrix;
}
};