问题分析

给定一个 m x n 的矩阵,要求按照顺时针螺旋顺序返回矩阵中的所有元素。矩阵可能为空或为单行/单列,需要按“右→下→左→上”的顺序循环遍历,直到所有元素被访问。

关键思路

采用边界指针法动态控制遍历范围,通过维护四个边界指针(top、bottom、left、right)来界定当前待遍历的环形区域。每完成一圈遍历后收缩边界,直到所有元素被访问。

解决步骤

初始化四个边界指针:

  • top = 0, bottom = m - 1
  • left = 0, right = n - 1

按顺时针方向分四步遍历:

  1. 从左到右遍历顶行,完成后top指针下移
  2. 从上到下遍历右列,完成后right指针左移
  3. 从右到左遍历底行(需检查top <= bottom),完成后bottom指针上移
  4. 从下到上遍历左列(需检查left <= right),完成后left指针右移

终止条件为top > bottom或left > right。

代码实现

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])
        result = []
        
        top, bottom = 0, m - 1
        left, right = 0, n - 1
        
        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

复杂度分析

时间复杂度:O(MN),需要遍历矩阵中的每个元素一次。 空间复杂度:O(1)(不计输出数组),仅使用常数个变量。

注意事项

  1. 第三步和第四步需检查是否存在有效行/列,避免重复添加或越界。
  2. 边界更新顺序要正确,防止遗漏角落元素。
  3. 空矩阵情况需特殊处理。
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐