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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        
        if(matrix.size()==0||matrix[0].size()==0)return vector<int>();
        int n=matrix.size();
        int m=matrix[0].size();
        vector<int>ret;
        int toward=0;
        int x=-1;
        int y=0;
        while(n>0&&m>0){
            if(toward==0){
                for(int i=0;i<m;i++){
                    x++;
                    ret.push_back(matrix[y][x]);
                }
                n--;
            }
            else if(toward==1){
                for(int i=0;i<n;i++){
                    y++;
                    ret.push_back(matrix[y][x]);
                }
                m--;
            }
            else if(toward==2){
                for(int i=0;i<m;i++){
                    x--;
                    ret.push_back(matrix[y][x]);
                }
                n--;
            }
            else{
                for(int i=0;i<n;i++){
                    y--;
                    ret.push_back(matrix[y][x]);
                }
                m--;
            }
            toward++;
            toward=toward%4;
        }
        return ret;
    }
};
View Code

 

posted @ 2013-10-05 23:11  懒猫欣  阅读(157)  评论(0编辑  收藏  举报