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
相关推荐
ada7_2 分钟前
LeetCode(python)78.子集
开发语言·数据结构·python·算法·leetcode·职场和发展
DeepVis Research15 分钟前
【AGI/Simulation】2026年度通用人工智能图灵测试与高频博弈仿真基准索引 (Benchmark Index)
大数据·人工智能·算法·数据集·量化交易
努力学算法的蒟蒻18 分钟前
day52(1.3)——leetcode面试经典150
算法·leetcode·面试
我送炭你添花18 分钟前
Pelco KBD300A 模拟器:06+5.串口实现的逻辑优化、配置管理与协议完善(二次迭代)
python·运维开发
databook20 分钟前
前注意加工:让你的图表抓住读者的眼球
python·数据分析·数据可视化
知行学思26 分钟前
Python配置管理完全指南:从dotenv到pydantic_settings
数据库·python·fastapi·环境变量·配置管理·pydantic·dotenv
leoufung31 分钟前
LeetCode 97. 交错字符串 - 二维DP经典题解(C语言实现)
c语言·算法·leetcode
郑同学的笔记1 小时前
【Eigen教程02】深入Eigen矩阵引擎:模板参数、内存布局与基础操作指南
c++·线性代数·矩阵·eigen
leiming63 小时前
c++ map容器
开发语言·c++·算法
杨校3 小时前
杨校老师课堂备赛C++信奥之模拟算法习题专项训练
开发语言·c++·算法