54. Spiral Matrix(剑指offer 19)



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

Example 1:

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

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

 

 

注意只有一行或者只有一列的情况

if (r1 < r2 && c1 < c2) {//避免只有一行,c1==c2的情况,避免只有一列,r1==r2的情况
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> list ;
        if(matrix.size()==0) return list;
        int rows =matrix.size();
        int cols = matrix[0].size();
        int c1 = 0,c2 = cols-1;
        int r1 = 0,r2 = rows-1;
        
        while(r1<=r2&&c1<=c2){
            for(int c=c1;c<=c2;c++) list.push_back(matrix[r1][c]);
            for(int r=r1+1;r<=r2;r++) list.push_back(matrix[r][c2]);
            if (r1 < r2 && c1 < c2) {//避免只有一行,c1==c2的情况,避免只有一列,r1==r2的情况
                for(int c=c2-1;c>=c1+1;c--) list.push_back(matrix[r2][c]);
                for(int r=r2;r>=r1+1;r--) list.push_back(matrix[r][c1]);
            }
            c1++;c2--;r1++;r2--;
        }
        return list;
    }
};

 

 

posted @ 2019-01-04 11:51  乐乐章  阅读(195)  评论(0编辑  收藏  举报