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]
.
注意边界。
class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> result; int m = matrix.size(); if (m == 0) return result; int n = matrix[0].size(); if (n == 0) return result; int min = (m < n ? m : n); int layer = min / 2; for (int i = 0; i < layer; ++i) { for (int j = i; j < n-1-i; ++j) { result.push_back(matrix[i][j]); } for (int j = i; j < m-1-i; ++j) { result.push_back(matrix[j][n-1-i]); } for (int j = n-1-i; j > i; --j) { result.push_back(matrix[m-1-i][j]); } for (int j = m-1-i; j > i; --j) { result.push_back(matrix[j][i]); } } if (min % 2 == 1) { if (m > n) { for (int i = layer; i <= m-1-layer; ++i) result.push_back(matrix[i][n/2]); } else { for (int i = layer; i <= n-1-layer; ++i) result.push_back(matrix[m/2][i]); } } } };