Kimi LeetCode 54. 螺旋矩阵 Python3实现
2026/9/7 10:35:50 网站建设 项目流程

LeetCode 54. 螺旋矩阵,经典边界收缩模拟题。

思路

维护四个边界,按顺时针方向逐层遍历:

top → ┌────────┐ │ 1 2 3 │ → right left ↓ │ 4 5 6 │ ↑ │ 7 8 9 │ └────────┘ bottom
  1. 从左到右遍历top行,然后top++
  2. 从上到下遍历right列,然后right--
  3. 从右到左遍历bottom行,然后bottom--
  4. 从下到上遍历left列,然后left++

边界交叉时结束。

Python3 实现

classSolution:defspiralOrder(self,matrix:List[List[int]])->List[int]:ifnotmatrixornotmatrix[0]:return[]m,n=len(matrix),len(matrix[0])top,bottom=0,m-1left,right=0,n-1result=[]whiletop<=bottomandleft<=right:# 1. 从左到右遍历 top 行forcolinrange(left,right+1):result.append(matrix[top][col])top+=1# 2. 从上到下遍历 right 列forrowinrange(top,bottom+1):result.append(matrix[row][right])right-=1# 3. 从右到左遍历 bottom 行(需检查是否还有行)iftop<=bottom:forcolinrange(right,left-1,-1):result.append(matrix[bottom][col])bottom-=1# 4. 从下到上遍历 left 列(需检查是否还有列)ifleft<=right:forrowinrange(bottom,top-1,-1):result.append(matrix[row][left])left+=1returnresult

复杂度

  • 时间复杂度:O(m × n),每个元素访问一次
  • 空间复杂度:O(1),不计输出数组

关键点

  1. 步骤 3 和 4 需要加if判断,防止在单行或单列矩阵时重复遍历
  2. 每遍历完一条边立即收缩对应边界
  3. 循环条件top <= bottom and left <= right确保不越界

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询