54.螺旋矩阵
matrix, simulation, https://leetcode.cn/problems/spiral-matrix/
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:

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

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]提示:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100
python
from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
visited = [[False] * n for _ in range(m)]
result = []
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
x, y = 0, 0
dir_idx = 0 # 初始方向为向右
for _ in range(m * n):
result.append(matrix[x][y])
visited[x][y] = True
dx, dy = directions[dir_idx]
next_x, next_y = x + dx, y + dy
# 检查边界条件和访问状态,如果合法,更新到下一个位置
if 0 <= next_x < m and 0 <= next_y < n and not visited[next_x][next_y]:
x, y = next_x, next_y
else:
dir_idx = (dir_idx + 1) % 4
dx, dy = directions[dir_idx]
x, y = x + dx, y + dy
return result
if __name__ == "__main__":
sol = Solution()
print(sol.spiralOrder([[1,2,3,4],[5,6,7,8],[9,10,11,12]]))