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
相关推荐
AI算法沐枫7 小时前
机器学习到底是什么?
人工智能·python·深度学习·机器学习·数据挖掘·大模型·#ai
小技与小术7 小时前
玩转Flask
开发语言·python·flask
SilentSamsara7 小时前
Python 性能优化:tracemalloc、profiling 与 C 扩展加速
开发语言·python·青少年编程·性能优化
冰小忆7 小时前
大驼峰命名规范和小驼峰命名规范的区别是什么?
开发语言·python
高洁017 小时前
知识图谱:AI的超级大脑
人工智能·python·数据挖掘·知识图谱
知识分享小能手8 小时前
Flask入门学习教程,从入门到精通,Flask智能租房——前期准备 知识点详解(5)
python·学习·flask
Curvatureflight8 小时前
【架构实战】生产级大模型 API 接入指南:流式响应(Streaming)异常处理与监控闭环
python·架构
cd_949217218 小时前
2026年扫描电子显微镜选型指南:易姆科特的核心优势与产品矩阵解析
人工智能·线性代数·矩阵
smj2302_796826529 小时前
解决leetcode第3943题递增后的数对数量
数据结构·python·算法·leetcode
deepin_sir9 小时前
06 Chroma_持久化与生产环境部署实战
python