思路:先计算好需要遍历多少层,每一层遍历四个方向,先从左往右,然后从上往下,然后从右往左,最后从下往上,所有层数都这样遍历,遍历过程中设计一个计数器,如果遍历完所有的元素,则跳出循环。
code:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> ret;
if(matrix.empty())return ret;
int nRow = matrix.size(), nCol = matrix[0].size();
int layer = min(nRow,nCol) / 2+1, num = 0;
for(int iLayer = 0;iLayer < layer;iLayer++){
for(int j = iLayer;j < nCol - iLayer;j++)
ret.push_back(matrix[iLayer][j]);
num += (nCol - 2*iLayer );
if(num >= nRow*nCol)break;
for(int i = iLayer+1;i<nRow - iLayer -1;i++)
ret.push_back(matrix[i][nCol - iLayer -1]);
num += (nRow - 2*iLayer -2);
if(num >=nRow*nCol)break;
for(int j = nCol - iLayer -1;j >= iLayer;j--)
ret.push_back(matrix[nRow - iLayer-1][j]);
num += (nCol - 2*iLayer);
if(num >= nRow*nCol)break;
for(int i = nRow - iLayer -2;i >= iLayer+1;i--)
ret.push_back(matrix[i][iLayer]);
num += (nRow - 2*iLayer -2);
if(num >= nRow*nCol)break;
}
return ret;
}
};