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

Solution

class Solution {
public:
    void help(vector<vector<int>>& matrix, vector<int>& res, int i1, int i2, int j1, int j2) {
        if ( i1 > i2 or j1 > j2 ) return;
        if ( i1 == i2 ) {
            for ( int j = j1; j <= j2; j++ ) res.push_back(matrix[i1][j]);
            return;
        }
        if ( j1 == j2 ) {
            for ( int i = i1; i <= i2; i++ ) res.push_back(matrix[i][j1]);
            return;
        }
        for ( int j = j1; j <= j2-1; j++ ) res.push_back(matrix[i1][j]);
        for ( int i = i1; i <= i2-1; i++ ) res.push_back(matrix[i][j2]);
        for ( int j = j2; j >= j1+1; j-- ) res.push_back(matrix[i2][j]);
        for ( int i = i2; i >= i1+1; i-- ) res.push_back(matrix[i][j1]);
        help(matrix, res, i1+1, i2-1, j1+1, j2-1);
        return;
    }
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        int m = matrix.size();
        if ( m == 0 ) return res;
        int n = matrix[0].size();
        if ( n == 0 ) return res;
        help(matrix, res, 0, m-1, 0, n-1);
        return res;
    }
};

results matching ""

    No results matching ""