LeetCode 59. 螺旋矩阵II

题目链接:点击这里

AC代码:

class Solution {
    
    
public:
    vector<vector<int>> generateMatrix(int n) {
    
    
        vector<vector<int>> a(n, vector<int>(n));

        int x = 0, y = 0;
        a[x][y] = 1;
        
        int tot = 1;
        while(tot < n * n)
        {
    
    
            while(y + 1 < n && !a[x][y + 1])    a[x][++y] = ++tot;
            while(x + 1 < n && !a[x + 1][y])    a[++x][y] = ++tot;
            while(y - 1 >= 0 && !a[x][y - 1])   a[x][--y] = ++tot;
            while(x - 1 >= 0 && !a[x - 1][y])   a[--x][y] = ++tot;
        }

        return a;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/108226390