思路:从外到内,方向按照 右->下->左->上 的方式进行填充,
class Solution{
public:
vector<vector<int>> generateMatrix(int n){
vector<vector<int>> res(n,vector<int>(n,0));//定义二维数组
int loop = n/2; //填充几圈
int mid = n/2; //螺旋矩阵最中间位置
int offset = 1; //偏移量
int startx = 0;
int starty = 0;
int count = 1;
int i,j;
while(loop--){
i = startx;
j = starty;
for( j = starty;j<n-offset;j++){
res[startx][j] = count++;
}
for( i = startx;i<n-offset;i++){
res[i][j] = count++;
}
for(;j>starty;j--){
res[i][j] = count++;
}
for(;i>startx;i--){
res[i][j] = count++;
}
offset++;
startx++;
starty++;
}
if(n%2){
res[mid][mid] = count;
}
return res;
}
};