跳转至

59.螺旋矩阵 II (Medium)*

题目描述*

给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例*

输入: 3

输出:

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

代码*

跟前面那个顺时针输出类似,还是设置四个边界填数字。

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0));
        int left = 0, right = n - 1, up = 0, bottom = n - 1;
        int i = 1;
        while(i <= n * n) {
            for(int j = left; j <= right; j++) {
                res[up][j] = i++;
            }
            up++;
            for(int j = up; j <= bottom; j++) {
                res[j][right] = i++;
            }
            right--;
            for(int j = right; j >= left; j--) {
                res[bottom][j] = i++;
            }
            bottom--;
            for(int j = bottom; j >= up; j--) {
                res[j][left] = i++;
            }
            left++;
        }
        return res;
    }
};

最后更新: July 23, 2022