[LeetCode]Spiral Matrix

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) {
        vector<int> ans;
        if(matrix.size()==0) return ans;
        int m=matrix.size()-1;
        int n=matrix[0].size()-1;
        int x=0;
        int y=0;
        int i;
        while(m>=x&&n>=y)
        {
            for(i=y;i<=n;i++) ans.push_back(matrix[x][i]); 
            for(i=x+1;i<=m;i++) ans.push_back(matrix[i][n]); 
            if(x!=m) for(i=n-1;i>=y;i--) ans.push_back(matrix[m][i]); 
            if(y!=n) for(i=m-1;i>x;i--) ans.push_back(matrix[i][y]); 
            x++;y++;m--;n--;
        }
        return ans;
    }
};

  

posted @ 2013-12-15 14:03  七年之后  阅读(167)  评论(0)    收藏  举报