当前位置:网站首页>Leetcode59. spiral matrix II (medium)

Leetcode59. spiral matrix II (medium)

2022-07-06 07:03:00 Heavy garbage

 Insert picture description here
 Insert picture description here
Ideas : simulation
Specific ideas : If you encounter an edge or a previously visited change of direction

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;
    }
};
原网站

版权声明
本文为[Heavy garbage]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060654495571.html