LeetCode刷题笔记--59. Spiral Matrix II

59. Spiral Matrix II

Medium

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

这道题好像自曾相识,应该是之前做过题目的变形。容易出现的问题就是写的时候边界没注意,内存报错。注意在转弯时不要重复写,另外每次for或者while完了以后,x或y都会超出1,需要减去1。这样就能运行出来了。注意0,1这两个特殊的输入。

下面是AC的代码。

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> z;
        z.clear();
        if(n==0)return z;
        if(n==1)
        {
            vector<int> t1;
            t1.push_back(1);
            z.push_back(t1);
            return z;
        }
        vector<int> t(n,0);
        vector<vector<int>> ans(n,t);
        int i=1;
        int x;
        int y;
        int minx=0;
        int maxx=n-1;
        int miny=0;
        int maxy=n-1;
        while(i<=n*n&&maxx>=minx&&maxy>=miny)
        {
            x=minx;
            y=miny;
            for(;x<=maxx;x++)
            {
                ans[y][x]=i;
                i++;
            }
            x--;
            for(y=miny+1;y<=maxy;y++)
            {
                ans[y][x]=i;
                i++;                 
            }
            y--;
            for(x=maxx-1;x>=minx;x--)
            {
                ans[y][x]=i;
                i++;
            }
            x++;
            for(y=maxy-1;y>=miny+1;y--)
            {
                ans[y][x]=i;
                i++;
            }
            y++;
            maxx--;
            minx++;
            miny++;
            maxy--;   
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/vivian0239/article/details/89669581