成功的人主宰时间,失败的人被时间主宰。

题目描述:

螺旋矩阵

给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

解题代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty()) return {};
int top = 0, left = 0,right = matrix[0].size()-1,bottom = matrix.size()-1;
while(true){

for(int l = left;l<=right;l++){
res.push_back(matrix[top][l]);
}
if(++top > bottom) break;
for(int l = top;l<=bottom;l++){
res.push_back(matrix[l][right]);
}
if(--right < left) break;
for(int l = right;l>=left;l--){
res.push_back(matrix[bottom][l]);
}
if(--bottom < top) break;
for(int l = bottom;l>=top;l--){
res.push_back(matrix[l][left]);
}
if(++left > right) break;
}
return res;
}
};

image-20231112213733403

解读与收获:

经典题目,刚开始做的时候陷入了很多误区,比如设计一个n来统计圈数(用来控制边界),绕了很多路。

解法:
先定义好上,下,左,右四个边界,然后在进行完每一次遍历后(从左到右,上到下,右到左,下到上),都让边界内敛一个单位,这样就能实现控制边界,当边界交叉时,说明结束。