54 螺旋矩阵

本文最后更新于:2026年5月10日 晚上

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

1
2
3
4
5
6
7
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]

示例 2:

1
2
3
4
5
6
7
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

Solution

官方题解思路:按层模拟

fig1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# @lc code=start
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return list()
res = list()
rows, columns = len(matrix), len(matrix[0])
left, right, top, bottom = 0, columns - 1, 0, rows - 1
while left<=right and top<=bottom:
for column in range(left, right+1):
res.append(matrix[top][column])
for row in range(top+1, bottom+1):
res.append(matrix[row][right])

if left < right and top < bottom:
for column in range(right-1, left, -1):
res.append(matrix[bottom][column])
for row in range(bottom, top, -1):
res.append(matrix[row][left])

left, right, top, bottom = left+1, right-1, top+1, bottom-1
return res
# @lc code=end

c++

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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>> &matrix) {
if (matrix.empty()) return {};

vector<int> res;
int rows = matrix.size(), cols = matrix[0].size();
int left = 0, right = cols - 1, top = 0, bottom = raws-1;

while (left <= right && top <= bottom) {
for (int col = left; col < right; ++col) {
res.push_back(matrix[top][col]);
}
for (int row = top+1; row < bottom; ++row) {
res.push_back(matrix[row][right]);
}
if (left < right && top < bottom) {
for (int col = right-1; col > left; --col) {
res.push_back(matrix[bottom][col]);
}
for (int row = bottom; row > top; --row) {
res.push_back(matrix[row][left]);
}
}
++left, --right;
++top, --bottom;
}
return res;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!