LeetCode 59. 螺旋矩阵 II【数组,模拟】中等-LMLPHP
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

示例 1:
LeetCode 59. 螺旋矩阵 II【数组,模拟】中等-LMLPHP

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

示例 2:

输入:n = 1
输出:[[1]]

提示:

  • 1 <= n <= 20

解法 数组+模拟

一种写法如下,用 0 0 0 n n n 作为边界,并用「判断 a n s ans ans 要填的格子」是否为 0 0 0 来判断是否越界:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ans(n, vector<int>(n));
        int c = 0, ns = n * n;
        int x = 0, y = -1;
        while (c < ns) {
            while (c < ns && y + 1 < n && !ans[x][y + 1]) 
                ans[x][++y] = ++c;
            while (c < ns && x + 1 < n && !ans[x + 1][y])
                ans[++x][y] = ++c;            
            while (c < ns && y - 1 >= 0 && !ans[x][y - 1])
                ans[x][--y] = ++c;
            while (c < ns && x - 1 >= 0 && !ans[x - 1][y])
                ans[--x][y] = ++c;
        }
        return ans;
    }
};

还可以这样写:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ans(n, vector<int>(n));
        int c = 0, ns = n * n;
        int x = 0;
        while (c < ns) {
            // 每次螺旋开始向右,y都等于x
            for (int y = x; y < n - x; ++y)
                ans[x][y] = ++c;
            // 向下
            for (int y = x + 1; y < n - x; ++y) 
                ans[y][n - x - 1] = ++c;
            // 向左
            for (int y = n - x - 2; y >= x; --y)
                ans[n - x - 1][y] = ++c;
            for (int y = n - x - 2; y > x; --y)
                ans[y][x] = ++c;
            ++x; // 加1层螺旋
        }
        return ans;
    }
};
10-10 06:02