LeetCode54题:螺旋矩阵(python3)

路径的长度即为矩阵中的元素数量,当路径的长度达到矩阵中的元素数量时即为完整路径,将该路径返回。

循环打印: "从左向右、从上向下、从右向左、从下向上" 四个方向循环打印。

python 复制代码
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return []
        r,c = len(matrix),len(matrix[0])
        res=[]
        left,right,top,bottom = 0,c-1,0,r-1
        while left<=right and top<=bottom:
            for i in range(left,right+1):
                res.append(matrix[top][i])
            for j in range(top+1,bottom+1):
                res.append(matrix[j][right])
            if left<right and top<bottom:
                for i in range(right-1,left,-1):
                    res.append(matrix[bottom][i])
                for j in range(bottom,top,-1):
                    res.append(matrix[j][left])
            left,right,top,bottom=left+1,right-1,top+1,bottom-1
        return res
相关推荐
招财小梗12 小时前
AI矩阵获客,品牌连锁落地方案揭秘
大数据·人工智能·矩阵
码流怪侠12 小时前
2026年8月GitHub热榜深度拆解:Agent Skills席卷开源圈,一个“技能包“收割5万星
算法·程序员·github
hold?fish:palm12 小时前
30 两两交换链表中的节点
数据结构·算法·链表
230万光年的思念12 小时前
分子动力学模拟参考文献
python
Nil20813 小时前
leetcode 98验证二叉搜索树
算法·leetcode·职场和发展
不正经学生13 小时前
C语言结构体:自定义数据类型,让变量打包出行
java·c语言·开发语言·数据结构·算法
HongXu_CaiYi13 小时前
0103-python相关-函数、文件
python
cxr82814 小时前
数学的本质:关系、模式与不变量的结构世界
人工智能·算法·机器学习
vortex514 小时前
从Conda到UV:Python项目依赖管理的现代演进
python·conda·uv
何以解忧,唯有..14 小时前
Python time 模块详解:时间处理与日期操作指南
开发语言·python