LeetCode 第 54 题:螺旋矩阵 Python 题解
本题解提供 LeetCode 第 54 题“螺旋矩阵”的 Python 代码实现,并对代码逻辑进行清晰解释。
def spiralOrder(matrix):
m, n = len(matrix), len(matrix[0])
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
visited = set()
res = []
x, y, d = 0, 0, 0
for _ in range(m * n):
res.append(matrix[x][y])
visited.add((x, y))
next_x, next_y = x + directions[d][0], y + directions[d][1]
if (
next_x < 0>= m
or next_y < 0>= n
or (next_x, next_y) in visited
):
d = (d + 1) % 4
next_x, next_y = x + directions[d][0], y + directions[d][1]
x, y = next_x, next_y
return res
代码解释:
- 使用
directions
列表存储四个方向的坐标变化。 - 使用
visited
集合记录已经访问过的坐标。 - 使用循环遍历矩阵中的所有元素。
- 在每次循环中:
- 将当前元素添加到结果列表
res
中。 - 将当前坐标添加到
visited
集合中。 - 计算下一个坐标。
- 如果下一个坐标超出边界或已经访问过,则改变方向,并重新计算下一个坐标。
- 更新当前坐标。
- 返回结果列表
res
。
1.1KB
文件大小:
评论区