54. Spiral Matrix

2018/05/12 leetcode 共 772 字,约 3 分钟

title

54. Spiral Matrix

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]

solution

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> v;
        
        if(matrix.size()==0) return v;
        int c1=0,c2=matrix[0].size()-1;
        int r1=0,r2=matrix.size()-1;
        while(c1<=c2&&r1<=r2){
            for(int i=c1;i<=c2;i++){
                v.push_back(matrix[r1][i]);
            }
            for(int i=r1+1;i<r2;i++){
                v.push_back(matrix[i][c2]);
            }
            if(r2>r1){
                for(int i=c2;i>=c1;i--){
                    v.push_back(matrix[r2][i]);
                }
            }
            if(c2>c1)
                for(int i=r2-1;i>r1;i--){
                    v.push_back(matrix[i][c1]);
                }
            c1++;
            c2--;
            r1++;
            r2--;
        }
        return v;
    }
};

Search

    Table of Contents