54 螺旋矩阵

本文最后更新于:2022年4月9日 中午

给定一个包含 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

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