Leetcode: 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].

不难,需要注意边界case。

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> result;
        int rows = matrix.size();
        if (rows == 0) return result;
        int cols = matrix[0].size();
        if (cols == 0) return result;
        
        int level = min(rows, cols);
        int i = 0;
        for (; i < level / 2; ++i) {
            for (int j = i; j < cols - i - 1; ++j) {
                result.push_back(matrix[i][j]);
            }
            for (int j = i; j < rows - i - 1; ++j) {
                result.push_back(matrix[j][cols-i-1]);
            }
            for (int j = cols - i - 1; j > i; --j) {
                result.push_back(matrix[rows-i-1][j]);
            }
            for (int j = rows - i - 1; j > i; --j) {
                result.push_back(matrix[j][i]);
            }
        }
        
        if (level % 2 != 0) {
            if (rows <= cols) {
                for (int j = i; j < cols - i; ++j) {
                    result.push_back(matrix[i][j]);
                }
            }
            else {
                for (int j = i; j < rows - i; ++j) {
                    result.push_back(matrix[j][i]);
                }
            }
        }
        
        return result;
    }
};

你可能感兴趣的:(LeetCode)