LeetCode 54. Spiral Matrix

来源:互联网 发布:unity3d手机游戏大全 编辑:程序博客网 时间:2024/06/06 01:19

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:

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]

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

class Solution {public:    vector<int> spiralOrder(vector<vector<int>>& matrix) {                int n=matrix.size(),x=0,y=0,m;        if(n>0) m=matrix[0].size();                vector<int> v(n*m);        if(n==0) return v;        int a[n][m];        for(int i=0;i<n;i++){            for(int j=0;j<m;j++){                a[i][j]=0;            }        }        v[0]=matrix[0][0];         a[0][0]=1;        int tot=0;        while(tot<n*m-1){            while(y+1<m&&a[x][y+1]==0) {                        v[++tot]=matrix[x][++y];                a[x][y]=1;            }            while(x+1<n&&a[x+1][y]==0) {                               v[++tot]=matrix[++x][y];                a[x][y]=1;            }            while(y-1>=0&&a[x][y-1]==0) {                v[++tot]=matrix[x][--y];                a[x][y]=1;            }            while(x-1>=0&&a[x-1][y]==0) {                v[++tot]=matrix[--x][y];                a[x][y]=1;            }                                }                return v;            }};

原创粉丝点击