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
相关推荐
深蓝电商API15 分钟前
Scrapy爬虫限速与并发控制最佳实践
爬虫·python·scrapy
Derrick__116 分钟前
淘宝MD5爬虫
爬虫·python
薛定谔的猫198219 分钟前
llama-index Embedding 落地到 RAG 系统
开发语言·人工智能·python·llama-index
夏鹏今天学习了吗21 分钟前
【LeetCode热题100(78/100)】爬楼梯
算法·leetcode·职场和发展
m0_748250031 小时前
C++ 信号处理
c++·算法·信号处理
Ro Jace1 小时前
电子侦察信号处理流程及常用算法
算法·信号处理
yuyanjingtao2 小时前
动态规划 背包 之 凑钱
c++·算法·青少年编程·动态规划·gesp·csp-j/s
nimadan122 小时前
**手机小说扫榜工具2025推荐,精准追踪榜单动态与题材风向
python·智能手机
编程武士2 小时前
Python 各版本主要变化速览
开发语言·python
傻啦嘿哟2 小时前
Python中的@property:优雅控制类成员访问的魔法
前端·数据库·python