#54
Medium
双指针

Spiral Matrix

按顺时针螺旋顺序返回矩阵中的元素。

按螺旋顺序返回矩阵元素。真正的核心不是复杂算法,而是四条边界如何稳定地收缩。

ArrayMatrixSimulation

题目定位

这题本质上是在按固定顺序不断收缩四条边界,因此虽然表面像模拟题,但核心仍然是边界指针控制。

关键观察

每走完一条边后,都必须立刻收紧对应边界,否则元素就会被重复访问或漏掉。

目标复杂度

O(mn) / O(1)

这题的解法思路怎么拆

1

维护四条边界:top、bottom、left、right。

2

按顺序遍历上边、右边、下边、左边。

3

每走完一条边,就收紧对应边界。

4

在遍历下边和左边前,一定重新判断边界是否仍然有效。

拿一个例子顺一遍

1

例如 [[1,2,3],[4,5,6],[7,8,9]]。

2

先读上边得到 1,2,3,再读右边得到 6,9。

3

接着逆向读下边得到 8,7,再向上读左边得到 4。

4

最后剩下中心点 5,因此答案是 [1,2,3,6,9,8,7,4,5]。

参考实现

Python
def spiralOrder(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
    order = []

    while top <= bottom and left <= right:
        for col in range(right - left + 1):
            order.append(matrix[top][left + col])
        top += 1

        for row in range(top, bottom + 1):
            order.append(matrix[row][right])
        right -= 1

        if top <= bottom:
            for col in range(right, left - 1, -1):
                order.append(matrix[bottom][col])
            bottom -= 1

        if left <= right:
            for row in range(bottom, top - 1, -1):
                order.append(matrix[row][left])
            left += 1

    return order

常见坑点

warning

在遍历下边和左边前忘了重新判断边界是否仍然有效。

warning

边界更新顺序写错,导致单元格被重复访问。

高频追问

如果题目改成生成螺旋矩阵而不是读取,思路怎么迁移?

如果矩阵不是规则矩阵,或者按行流式到达,会有什么变化?

继续刷相关题

先把 双指针 这个模式刷成体系,再去做更难变体。

view_week回到模式页
LeetCode 54. Spiral Matrix 题解思路 | Interview AiBox