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


LeetCode 54. Spiral Matrix_第1张图片

The line marked as red need to pay special attention! (It is very easy to forget it!)

I personally think this question is pretty hard...... It has a lot of details to deal with in a limited time and easy to make mistakes.

#include <vector>
#include <iostream>
using namespace std;

vector<int> spiralOrder(vector< vector<int> >& matrix) {
    if(matrix.size() == 0) return {};
    if(matrix[0].size() == 0) return {};
    int m = matrix.size();
    int n = matrix[0].size();
    vector<int> res;

    int layer = m < n ? m : n;
    // this is only for even m and n. 
    for(int i = 0; i < layer/2; ++i) {
        for(int j = i; j < n - 1 - i; ++j) {
            res.push_back(matrix[i][j]);
        }

        for(int j = i; j < m - 1 - i; ++j)
            res.push_back(matrix[j][n-1-i]);

        for(int j = n - 1 - i; j > i; --j)
            res.push_back(matrix[m-1-i][j]);

        for(int j = m - 1 - i; j > i; --j)
            res.push_back(matrix[j][i]);
    }
    // ends for even m and n.
    if(layer % 2 != 0) {
        if(m > n) {
            for(int i = layer/2; i <= m - 1 - layer/2; ++i) {
                res.push_back(matrix[i][n/2]);
            }
        } else {
            for(int i = layer/2; i <= n - 1 - layer/2; ++i) {
                res.push_back(matrix[m/2][i]);
            }
        }
    }
    return res;
}
 int main(void) {
    vector< vector<int> > matrix{
        {1, 2, 3, 4, 5},
        {1, 2, 3, 4, 5},
        {1, 2, 3, 4, 5},
        {1, 2, 3, 4, 5},
        {1, 2, 3, 4, 5}};
    vector<int> res = spiralOrder(matrix);
    for(int i = 0; i < res.size(); ++i) {
         cout << "index i: " << i << " " << res[i] << endl;
    }
    cout << endl;
}



你可能感兴趣的:(LeetCode 54. Spiral Matrix)