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
相关推荐
大数据魔法师2 小时前
Streamlit(二十三)- 教程(二)- 动态导航
python·web
心中有国也有家5 小时前
GE图引擎深度解析——CANN的计算图优化与执行引擎
人工智能·pytorch·python·学习·numpy
地平线开发者6 小时前
profiler debug 工具用法与高一致性策略
算法·自动驾驶
卷毛的技术笔记6 小时前
告别硬编码!Spring AI Alibaba 实现 AI Agent 智能工具调用(Tool Calling)
java·人工智能·后端·python·spring·ai编程
编程大师哥6 小时前
匿名函数 lambda + 高阶函数
java·python·算法
vb2008116 小时前
FastAPI APIRouter
开发语言·python
adrninistrat0r6 小时前
Java调用链MCP分析工具
java·python·ai编程
我叫袁小陌7 小时前
算法解题思路指南
算法
地平线开发者7 小时前
Conv+BN+Add+ReLU 融合机制简介
算法·自动驾驶