题目描述:
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
解题分析:
采用模拟的方法,首先用left、top、right、bottom表示外面一圈的row、col的最小最大值,每次模拟一圈取值,然后left++、top++、right–、bottom++就表示往里一圈,然后继续模拟取值即可。需要注意的是这样每次模拟是至少是一个2*2的矩阵,所以需要考虑lefttop或者topbottom的情形。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
if(matrix.size()==0)
return {};
vector<int> spiralOrderVec;
int left=0, top=0, right=matrix[0].size()-1, bottom=matrix.size()-1;
while(left<=right && top<=bottom){
int row=top, col=left;
if(left==right){
while(row<=bottom){
spiralOrderVec.push_back(matrix[row][col]);
row++;
}
break;
}
else if(top==bottom){
while(col<=right){
spiralOrderVec.push_back(matrix[row][col]);
col++;
}
break;
}
row=top, col=left;
while(col<=right){
spiralOrderVec.push_back(matrix[row][col]);
col++;
}
row=top+1,col=right;
while(row<=bottom){
spiralOrderVec.push_back(matrix[row][right]);
row++;
}
col=right-1,row=bottom;
while(col>=left){
spiralOrderVec.push_back(matrix[bottom][col]);
col--;
}
row=bottom-1,col=left;
while(row>top){
spiralOrderVec.push_back(matrix[row][left]);
row--;
}
left++,right--,top++,bottom--;
}
return spiralOrderVec;
}
};