力扣59-螺旋矩阵

螺旋矩阵

题目链接

class Solution {
public:
    vector> generateMatrix(int n) {
        vector>res(n, vector(n, 0));
        int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};  //方向偏移数组
        int x = 0, y = 0;  //当前位置
        for(int i = 1, d = 0; i <= n*n; i++)
        {
            res[x][y] = i; 
            int a = x + dx[d], b = y + dy[d]; 
            if(a <0 || a == n || b < 0 || b == n || res[a][b]){  //出界或者该位置已经被走过
                d = (d + 1) % 4;   //更改方向
                a = x + dx[d], b = y + dy[d];  //下一个要走的位置
            }
            x = a, y = b;    
        }
        return res;
    }
};

你可能感兴趣的:(算法-每日一练,leetcode,矩阵,算法)