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 ]
]


思路:

四条线路法,定义up,right,down,left四个变量,先走最上面,再走最右边,再走最下面,再走最左边,条件结束标志为左等于右,上等于下。

代码:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int>res;
        
        if(matrix.empty() || matrix[0].empty()){
            return res;
        }
        int m=matrix.size();
        int n=matrix[0].size();
        int left=0,right=n-1;
        int up=0,down=m-1;
        
        while(up<=down&&left<=right){
            for(int i=left;i<=right;i++){
                res.push_back(matrix[up][i]);
            }
            
            for(int i=up+1;i<=down;i++){
                res.push_back(matrix[i][right]);
            }
            
            if(up==down||left==right){    
                break;
            }
                for(int i=right-1;i>=left;i--){
                    res.push_back(matrix[down][i]);
                }
            
                for(int i=down-1;i>=up+1;i--){
                    res.push_back(matrix[i][left]);
                }
            up++;
            right--;
            down--;
            left++;
        }
        
        return res;
    }
};


posted @ 2015-10-25 09:15  JSRGFJZ6  阅读(100)  评论(0编辑  收藏  举报