原题目:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/
思路:
记录上下和左右边界,每次边界--,如果超出边界就退出
代码:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.empty()) return {};
vector <int> res;
int rl = 0, rh = matrix.size()-1; //矩阵上下边缘
int cl = 0, ch = matrix[0].size()-1; //矩阵左右边缘
while(1){
for(int i=cl; i<=ch; i++) res.push_back(matrix[rl][i]);//从左往右
if(++rl > rh) break; //若超出边界,退出
for(int i=rl; i<=rh; i++) res.push_back(matrix[i][ch]);//从上往下
if(--ch < cl) break;
for(int i=ch; i>=cl; i--) res.push_back(matrix[rh][i]);//从右往左
if(--rh < rl) break;
for(int i=rh; i>=rl; i--) res.push_back(matrix[i][cl]);//从下往上
if(++cl > ch) break;
}
return res;
}
};