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<matrix.size() && ny >= 0 && ny<matrix[0].size() && matrix[nx][ny] != inf))
                f = (f + 1) & 3;
            x += dx[f], y += dy[f];
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/bendaai/article/details/80190005