leetcode 54. Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

这题是个模拟,怎么写都行。

class Solution {
public:
    int dx[4]={1,0,-1,0};
    int dy[4]={0,1,0,-1};
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        int n=matrix.size();
        if(n==0)return res;
        int m=matrix[0].size();
        if(m==0)return res;
        res.push_back(matrix[0][0]);
        if(m*n==1)return res;
        matrix[0][0]=INT_MIN;
        int d=0,x=0,y=0;
        int cnt=0;
        while(true){
            if(cnt>4)break;
            int nx=x+dx[d],ny=y+dy[d];
            if(nx<0||ny<0||nx>m-1||ny>n-1){
                d=(d+1)%4;cnt++;
                continue;
            }
            if(matrix[ny][nx]==INT_MIN){
                d=(d+1)%4;cnt++;
                // nx=x+dx[d];ny=y+dy[d];
                // if(!matrix[ny][nx])break;
                continue;
            }
            res.push_back(matrix[ny][nx]);
            matrix[ny][nx]=INT_MIN;
            x=nx,y=ny;cnt=0;
        }
        return res;
    }
};
posted @ 2020-08-01 18:12  winechord  阅读(81)  评论(0编辑  收藏  举报