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
相关推荐
玫幽倩4 分钟前
2026黄河流域公安院校-电子物证单项赛(程序逆向分析+服务器取证)
运维·服务器·python·电子取证·逆向·程序分析·服务器取证
北斗落凡尘7 分钟前
LangGraph 入门实战(4)
python·langchain
闲研随记11 分钟前
【文献阅读 ICLR 2026】RL算法:Co-Rewarding
算法
青山木20 分钟前
Hot 100 --- 最小栈
java·数据结构·算法·leetcode
疯狂打码的少年24 分钟前
【数据结构】栈的应用:表达式求值(后缀表达式)
java·数据结构·笔记·算法
liwulin050627 分钟前
【PYTHON】使用Selenium + ChromeDriver以及XPATH语法
开发语言·python·selenium
copyer_xyf29 分钟前
Agentic RAG 实战:PostgreSQL + LangGraph 一条链路
python·postgresql·agent
HiDev_34 分钟前
【非标自动化】plc执行顺序问题、扫描周期问题
深度学习·算法·机器学习
动力 continue35 分钟前
Python 元类与异常类:类的“制造工厂”与“报错定制师”
开发语言·python·制造
147API44 分钟前
Python批量生成蒸馏数据,并发、重试、幂等和断点续跑
开发语言·jvm·python