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].
注意几点: 1)spiral 总共转了几圈 2) 最后一圈的时候如果是“横”“竖”需要处理好边界
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> res; int rows = matrix.size(); if(rows == 0) return res; int columns = matrix[0].size(); if( columns ==0) return res; int lays = rows > columns ? (columns+1)/2 : (rows+1) /2; bool single = rows > columns ? columns%2 :rows%2 ; for(int lay = 0; lay < lays ; lay++) { int topRow = lay; int rightColumn = columns - 1 - lay; //process the top row for(int i = lay ; i <= rightColumn ; i++) res.push_back(matrix[topRow][i]); //process the right column ,not include the first of the right column element for(int i = lay +1 ; i <= rows - 1 - lay ; i++) res.push_back(matrix[i][rightColumn]); if(lay == lays -1 && single) continue ; //process the bottom row, not include the last of the bottom row element for(int i = rightColumn - 1 ;i >= lay ; i--) res.push_back(matrix[rows-1-lay][i]); //process the left; for(int i = rows - 1 - lay -1 ;i > lay ; i--) res.push_back(matrix[i][lay]); } return res; } };