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
相关推荐
RSABLOCKCHAIN1 小时前
AI Agents in LangGraph-2
人工智能·python
WA内核拾荒者2 小时前
WhatsApp 账号异常检测的自动化告警系统设计
数据库·python·自动化
imuliuliang2 小时前
关于数据结构在算法设计中的核心作用解析7
算法
码流怪侠3 小时前
【GitHub】Bend:让 GPU 并行编程像写 Python 一样简单
python·github
2401_894915534 小时前
GEO 搜索优化完整源码从零部署:环境配置、集群搭建全流程
开发语言·python·tcp/ip·算法·unity
普通网友5 小时前
共识算法实现:从工作量证明到权益证明的演进
算法·区块链·共识算法
zhiSiBuYu05175 小时前
Python3 模块开发与应用实战指南
python
ldmd2846 小时前
地图生成算法(噪声篇-Perlin,Simplex,Value noise)
算法·go·地图生成