题目:
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) { vector<int> ret; const int m = matrix.size(); if (m<1) return ret; const int n = matrix[0].size(); const int circle = std::min(n, m)/2; for ( int c=0; c<circle; ++c ) { // traversal a circle // up row for ( int col=c; col<n-c; ++col ) ret.push_back(matrix[c][col]); // right col for ( int row=c+1; row<m-c-1; ++row ) ret.push_back(matrix[row][n-1-c]); // down row for ( int col=n-1-c; col>=c; --col ) ret.push_back(matrix[m-1-c][col]); // left col for ( int row=m-c-2; row>c; --row ) ret.push_back(matrix[row][c]); } // if odd if ( std::min(n, m) & 1 ){ if ( m>=n ){ for ( int row=circle; row<m-circle; ++row ) ret.push_back(matrix[row][circle]); } else{ for ( int col=circle; col<n-circle; ++col ) ret.push_back(matrix[circle][col]); } } return ret; } };
tips:
1. 首先确定要绕几圈:取行和列中小的,除以2,得到绕几圈(如果是偶数正好绕完;奇数剩中间的一行或一列)
2. 按照题中给的顺序绕(上 右 下 左)
3. ‘绕’循环出来之后,判断行列中较小的那个是奇数还是偶数(位运算判断):如果是偶数则不用处理;如果是奇数,需要判断剩下的是‘一行’还是‘一列’(行列相等的情况可以归到剩下一行的情况中)
完毕。
===========================================
第二次过这道题,第一次没有想到分奇数偶数讨论;考虑了之后AC了。
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> ret; if ( matrix.empty() ) return ret; const int M = matrix.size(); // row const int N = matrix[0].size(); // column const int C = min(M,N)/2; // circle for ( int i=0; i<C; ++i ) { // north for ( int p=i; p<N-i; ++p ) ret.push_back(matrix[i][p]); // east for ( int p=i+1; p<M-i-1; ++p ) ret.push_back(matrix[p][N-1-i]); // south for ( int p=i; p<N-i; ++p ) ret.push_back(matrix[M-1-i][N-1-p]); // west for ( int p=i+1; p<M-i-1; ++p ) ret.push_back(matrix[M-1-p][i]); } if ( min(M,N) & 1 ) { if ( M<N ) { for ( int i=C; i<N-C; ++i) ret.push_back(matrix[C][i]); } else { for ( int i=C; i<M-C; ++i ) ret.push_back(matrix[i][C]); } } return ret; } };