思路
- 直接模拟程序运行,设置(rowbegin,rowend,colbegin,colend)变量。注意:要判断是否遍历过。 参考
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if(matrix.size() == 0) return {};
int colbegin = 0,colend = matrix[0].size()-1;
int rowbegin = 0,rowend = matrix.size()-1;
while(rowbegin <= rowend && colbegin <= colend){
for(int i = colbegin; i <= colend; i++){
res.push_back(matrix[rowbegin][i]);
}
rowbegin++;
//这里也可以加入判断,但实际上没必要
for(int i = rowbegin; i <= rowend; i++){
res.push_back(matrix[i][colend]);
}
colend--;
if(rowbegin <= rowend){ //判断
for(int i = colend; i >= colbegin; i--){
res.push_back(matrix[rowend][i]);
}
rowend--;
}
if(colbegin <= colend){
for(int i = rowend; i >= rowbegin; i--){
res.push_back(matrix[i][colbegin]);
}
colbegin++;
}
}
return res;
}
};