Leetcode:59. 螺旋矩阵 II

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

示例:

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

解题思路:

模拟题,将初始位置设置成(0,-1)。初始的移动量R=n,D=n-1,L=n-1,U=n-2。每走完一圈R,D,L,U都减2。当移动的方向没有移动量时,退出循环。

Leetcode:59. 螺旋矩阵 II

C++代码
class Solution{
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0));
        pair<int, int> pos(0, -1);
        int R = n, D = n - 1, L = n - 1, U = n - 2;
        int num = 1, i;
        while (1) {
            if (R == 0) break;
            for (i = 1; i <= R; i++) {
                pos.second++;
                res[pos.first][pos.second] = num;
                num++;
            }
            if (D == 0) break;
            for (i = 1; i <= D; i++) {
                pos.first++;
                res[pos.first][pos.second] = num;
                num++;
            }
            if (L == 0) break;
            for (i = 1; i <= D; i++) {
                pos.second--;
                res[pos.first][pos.second] = num;
                num++;
            }
            if (U == 0) break;
            for (i = 1; i <= D; i++) {
                pos.first--;
                res[pos.first][pos.second] = num;
                num++;
            }
            R -= 2; D -= 2; U -= 2; L -= 2;
        }
        return res;
    }
};