54. 螺旋矩阵

题目

image-20240911161943594

解法

这道题目的解法其实并不是很难,自己最开始写的时候是想着一个循环中只是处理数据,对于下个要添加进去的数据则是需要有很多辅助if去判断,问题就出在这里,正确的、容易理解发解法就是下面这个

代码

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

vector<int> Array::spiralOrder(vector<vector<int>>& matrix)
{
int m = matrix.size();
int n = matrix[0].size();

if (m == 0 || n == 0) return {};

vector<int> res;
int left = 0, right = n - 1, top = 0, buttom = m - 1;
while (left <= right && top <= buttom)
{
//在一次循环中将一次顺时针的四个方向遍历完成

//向右遍历的部分
for (int column = left; column <= right; column++)
{
res.push_back(matrix[top][column]);
}

//向下遍历的部分
for (int row = top + 1; row <= buttom; row++)
{
res.push_back(matrix[row][right]);
}

//向左和向上遍历的部分
if (left < right&& top < buttom)
{
for (int column = right - 1; column > left; column--)
{
res.push_back(matrix[buttom][column]);
}

for (int row = buttom; row > top; row--)
{
res.push_back(matrix[row][left]);
}
}

//缩圈
++left;
++top;
--right;
--buttom;
}
return res;
}