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
相关推荐
m0_734949791 天前
MySQL如何配置定时清理过期备份文件_find命令与保留周期策略
jvm·数据库·python
m0_514520571 天前
MySQL索引优化后性能没提升_通过EXPLAIN查看索引命中率
jvm·数据库·python
H Journey1 天前
Python 国内pip install 安装缓慢
python·pip·install 加速
kobesdu1 天前
人形机器人SLAM:技术挑战、算法综述与开源方案
算法·机器人·人形机器人
王_teacher1 天前
机器学习 矩阵求导 完整公式+严谨推导
人工智能·线性代数·考研·机器学习·矩阵·线性回归
Polar__Star1 天前
如何在 AWS Lambda 中正确使用临时凭证生成 S3 预签名 URL
jvm·数据库·python
m0_743623921 天前
React 自定义 Hook 的命名规范与调用规则详解
jvm·数据库·python
FreakStudio1 天前
无硬件学LVGL—定时器篇:基于Web模拟器+MicroPython速通GUI开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
椰羊~王小美1 天前
随机数概念及算法
算法
阿Y加油吧1 天前
算法实战笔记:LeetCode 169 多数元素 & 75 颜色分类
笔记·算法·leetcode