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
相关推荐
IPdodo_2 分钟前
跨境 API 调用不稳定怎么办:出口、超时重试与链路监控的实践
网络·python·网络协议
Madison-No726 分钟前
搭建项目测试环境
linux·运维·服务器·python
计算机编程-吉哥1 小时前
YOLO26 vs YOLO11 vs YOLOv8:深度学习咖啡果实成熟度分割系统【计算机毕业设计选题推荐】
人工智能·python·深度学习·yolo·django·毕业设计
彧azz1 小时前
算法设计与分析:贪心与动态规划
数据结构·学习·算法·贪心算法·动态规划
大衛說1 小时前
11 · 异常处理与日志
python
auto_go2 小时前
Python 实战指南(7)——账本动不动就崩?先把“魔法字符串”和“裸报错”干掉
python
Beyond_System|系统之外2 小时前
【学编程】Python基础编程题100道(21-60)
开发语言·python·算法
根目录下的猫2 小时前
RK3588适配的轻量级AI模型推荐
人工智能·后端·python·目标检测
wno7043 小时前
Spring Security权限控制
java·python·spring
ShineWinsu3 小时前
对于Coze—AI:SDK的解析
人工智能·python·ai·sdk·项目·coze·字节跳动