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
相关推荐
旖-旎1 分钟前
深搜练习(组合总和)(7)
c++·算法·深度优先·力扣
捉鸭子7 分钟前
某音a_bogus vmp逆向
爬虫·python·web安全·node.js·js
小O的算法实验室12 分钟前
2026年ASOC,基于人工势场的差分进化算法改进框架,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
爱学习的张大17 分钟前
具身智能论文精读(五):OpenVLA
人工智能·算法
曲幽18 分钟前
FastAPI 生产环境静态文件完全指南:从 /favicon.ico 404 到 HSTS 混合内容,一次全根治
python·fastapi·web·static·media·404·hsts·favicon·url_for
Dontla20 分钟前
Python asyncpg库介绍(基于Python asyncio的PostgreSQL数据库驱动)连接池、SQLAlchemy
数据库·python·postgresql
zh15702328 分钟前
如何编写动态SQL存储过程_使用sp_executesql执行灵活查询
jvm·数据库·python
2401_8242226932 分钟前
SQL报表统计数据量巨大_分批统计策略
jvm·数据库·python
X566135 分钟前
mysql如何处理连接数过多报错_调整max_connections参数
jvm·数据库·python
风落无尘1 小时前
第二章《概率与生存》完整学习资料
人工智能·矩阵·概率论