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]
.
代码:
class Solution{ public: void doit(int start,int row,int col,vector<int>& res,vector<vector<int> > matrix){ } vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int> res; if(matrix.empty()) return res; int row=matrix.size()-1; int col=matrix[0].size()-1; if(row==-1||col==-1) return res; int start=0; int s=min(row,col); while(row>=0&&col>=0&&start<=s){ if(res.size()==(matrix.size()*matrix[0].size())) break; if(row==start&&col==start) {res.push_back(matrix[start][start]);return res;}//只有一个数字 if(row==start){//只有一行 for (int i=start;i<=col;++i) res.push_back(matrix[start][i]); break; } if(col==start){//只有一列 for (int i=start;i<=row;++i) res.push_back(matrix[i][start]); break; } for (int i=start;i<=col;++i) res.push_back(matrix[start][i]); for (int j=start+1;j<=row;++j) res.push_back(matrix[j][col]); for (int m=col-1;m>=start;--m) res.push_back(matrix[row][m]); for (int n=row-1;n>=start+1;--n) res.push_back(matrix[n][start]); ++start; --row; --col; } return res; } };