美文网首页
spiral-matrix-ii

spiral-matrix-ii

作者: DaiMorph | 来源:发表于2019-07-24 22:08 被阅读0次
    class Solution {
    public:
        vector<vector<int> > generateMatrix(int n) {
            vector<vector<int>>res(n,vector<int>(n));
            if(n==0)return res;
            int num=1;
            int left=0,right=n-1,up=0,down=n-1;
            while(left<=right&&up<=down)
            {
                for(int j=left;j<=right;j++)res[up][j]=num++;
                for(int i=up+1;i<=down;i++)res[i][right]=num++;
                for(int j=right-1;j>=left&&up!=down;j--)res[down][j]=num++;
                for(int i=down-1;i>up&&left!=right;i--)res[i][left]=num++;
                up++,down--,left++,right--;
            }
            return res;
        }
    };
    

    相关文章

      网友评论

          本文标题:spiral-matrix-ii

          本文链接:https://www.haomeiwen.com/subject/agcqrctx.html