参考链接:代码随想录->螺旋矩阵II
关键是学视频链接里面的编码思想,然后背下来
class Solution {
public:vector<vector<int>> generateMatrix(int n) {vector<vector<int>> res=vector(n,vector<int>(n,0));int sx=0,sy=0,offset=1,loop,i,j,mid=n/2,cnt=1;for(loop=n/2;loop;loop--){i=sx;j=sy;for(j=sy;j<n-offset;++j){res[sx][j]=cnt++;}for(i=sx;i<n-offset;++i){res[i][j]=cnt++;}for(;j>sy;--j){res[i][j]=cnt++;}for(;i>sx;--i){res[i][j]=cnt++;}sx++;sy++;offset++;}if(n%2==1){res[mid][mid]=cnt;}return res;}
};