打印螺旋矩阵

方向数组 dx, dy

什么时候改变方向

  • 越界
  • 已经访问过 -> bool数组来辅助判断

class Solution {
public:
    int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0 , -1 ,0};
    
    vector spiralOrder(vector > &matrix) {
        vector res;
        int n = matrix.size(), m = matrix[0].size();
        if(!n || !m) return res;  // 特判下
        vector> st(n, vector(m, false));
        
        for(int i = 0, x = 0, y = 0, d = 0; i < n  * m; i ++)
        {
            res.push_back(matrix[x][y]);
            st[x][y] = true;
            
            int nx = x + dx[d], ny = y + dy[d];
            if(nx < 0 || nx >= n || ny < 0 || ny >= m ||st[nx][ny])
            {
                d = (d + 1)  % 4;
                nx = x + dx[d], ny = y + dy[d];
            }
            x  = nx, y = ny;
        }
        
        return res;
    }
};

你可能感兴趣的:(打印螺旋矩阵)