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
相关推荐
程序员小远33 分钟前
接口测试知识总结
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
HanhahnaH34 分钟前
各数据结构操作的时间复杂度汇总
数据结构·算法
增量星球37 分钟前
一个 Python 脚本 + LLM 怎么替代向量检索?ProjQA 技能架构原理深度解析
开发语言·python·架构·embedding·skill
SamChan9043 分钟前
Python+PyMuPDF提取PDF表格并翻译:表格结构检测与双语重建实战
windows·python·ai·pdf·wpf
weixin_3077791344 分钟前
PySpark根据输入的表名和过滤条件生成 INSERT 语句
python·spark·云计算·big data
Yzzz-F1 小时前
CF2023D
c++·算法·dp
GodSure09141 小时前
Java单一职责原则SRP详解
java·python·单一职责原则
小小帅呀1 小时前
学习 VLA 第6天:SWIN VIT算法原理以及复现
学习·算法
Mojitocean1 小时前
Win开发环境配置(持续更新)
开发语言·python