Leetcode 54 Spiral Matrix

2018-01-12 15:03:34 浏览数 (1)

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

For example, Given the following matrix:

代码语言:javascript复制
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

Subscribe to see which companies asked this question

旋转取数,模拟,注意边界情况

代码语言:javascript复制
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        int m=matrix.size();
        if(m==0) return result;
        int n=matrix[0].size(),x=0,y=0;
        for(;x<m && y<n;x  ,y  ,m--,n--)
        {
            for(int i=y;i<n;i  ) result.push_back(matrix[x][i]);
            for(int i=x 1;i<m;i  ) result.push_back(matrix[i][n-1]);
            for(int i=n-2;i>=y && x!=m-1;i--) result.push_back(matrix[m-1][i]);//x==m-1时此行已填
            for(int i=m-2;i>x && y!=n-1;i--) result.push_back(matrix[i][y]);//i>x,因为首行第一个元素开始已填
        }
        return result;
    }
};

0 人点赞