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
相关推荐
秋说33 分钟前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy1 小时前
力扣61.旋转链表
算法·leetcode·链表
卡卡卡卡罗特3 小时前
每日mysql
数据结构·算法
chao_7893 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
烛阴3 小时前
Python装饰器解除:如何让被装饰的函数重获自由?
前端·python
noravinsc4 小时前
django 一个表中包括id和parentid,如何通过parentid找到全部父爷id
python·django·sqlite
lifallen4 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法
lixzest4 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
ajassi20004 小时前
开源 python 应用 开发(三)python语法介绍
linux·python·开源·自动化
EndingCoder4 小时前
搜索算法在前端的实践
前端·算法·性能优化·状态模式·搜索算法