Leetcode 54. 螺旋矩阵

模拟螺旋的路线,标记已访问的数据,然后循环即可

class Solution {
public:
    int dx[4] = { 0,1,0,-1 }, dy[4] = { 1,0,-1,0 }, f = 0;
    const int inf = 0x3f3f3f3f;
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> ans;
        int cnt = matrix.size() ? matrix.size()*matrix[0].size() : 0, x = 0, y = 0;
        while (cnt--) {
            ans.push_back(matrix[x][y]); matrix[x][y] = inf;
            int nx = x + dx[f], ny = y + dy[f];
            if (!(nx >= 0 && nx= 0 && ny0].size() && matrix[nx][ny] != inf))
                f = (f + 1) & 3;
            x += dx[f], y += dy[f];
        }
        return ans;
    }
};

你可能感兴趣的:(Leetcode 54. 螺旋矩阵)