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
相关推荐
the局外人20 分钟前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
__underline__23 分钟前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python
风落青芜36 分钟前
链式二叉树的实现与基本操作
c语言·开发语言·数据结构·算法
用户0332126663671 小时前
使用 Python 轻松移除 Excel 文档中的重复行
python·excel
LiaoWL1231 小时前
从零搭一个 RAG 知识库(二):换上语义 Embedding——BGE 实测与阈值重校准
python·大模型·numpy·embedding·向量检索·rag
Dmz丶2 小时前
前端转 AI 100 天 Day 48:向量数据库——100 万向量的毫秒级检索
python
青少儿编程课堂2 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:中国剩余定理解析
c++·python·算法·bfs·信息学竞赛
菜鸟~noob2332 小时前
[AI]间章:系列走到这里,聊聊后面的规划、造卡需要的软件平台,以及为什么我要先暂停更新
人工智能·python·fpga开发·django·pygame
TomEval12 小时前
【测AI】第26篇:线上模型监控与告警体系 — 测试不是终点
人工智能·python·功能测试·ai
prince_zxill13 小时前
PEP 751 pylock.toml 实测:pip 26.3 装 6 个包版本全钉死,但 [web] 选不中任何东西
python·pip·依赖管理·pep 751