leetcode59. 螺旋矩阵 II(中等)

leetcode59. 螺旋矩阵 II(中等)_第1张图片
在这里插入图片描述
思路:模拟
具体思路:如果遇到边缘或者遇到之前访问过的改变方向

class Solution {
public:
    int xy[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
    vector<vector<int>> generateMatrix(int n) {

        vector<vector<int>> ans(n, vector<int>(n));
        vector<vector<int>> flag(n, vector<int>(n));
        int x = 0, y = 0, index = 0;
        for (int i = 1; i <= n * n; ++i) {
            
            ans[x][y] = i;
            flag[x][y] = 1;
            int newx = x + xy[index][0], newy = y + xy[index][1];
            if (newx < 0 || newx >= n || newy < 0 || newy >= n || flag[newx][newy]) {
                index = (index + 1) % 4;
            }
            x = x + xy[index][0];
            y = y + xy[index][1];
        }
        return ans;
    }
};

你可能感兴趣的:(#,模拟,矩阵,算法,数据结构)