把 [[1,2,3],[4,5,6]] 按螺旋展开,第一条边读到 1、2、3。接着沿最右列向下只剩 6,再沿底边向左拿到 5、4。这时两行都读完了,左侧已经没有路可走。
可以把没有读过的格子看作一个越来越小的长方形。每次读完上边就抬高上边界,读完右边就往左收。接下来要向左、向上时,各看一眼剩余范围。这样只剩一行或一列时,也不会再把同一个角读一遍。
class Solution:
def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
if not matrix or not matrix[0]:
return []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
result = []
while top <= bottom and left <= right:
for col in range(left, right + 1):
result.append(matrix[top][col])
top += 1
for row in range(top, bottom + 1):
result.append(matrix[row][right])
right -= 1
if top <= bottom:
for col in range(right, left - 1, -1):
result.append(matrix[bottom][col])
bottom -= 1
if left <= right:
for row in range(bottom, top - 1, -1):
result.append(matrix[row][left])
left += 1
return result
m 行 n 列总共走过 mn 个格子,时间 O(mn)。除了用于返回的列表,只需要四个边界,辅助空间 O(1)。

