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
相关推荐
wdloumiga11 小时前
使用 Construct 3零基础做一些2D小游戏
python·游戏·游戏2d
_Narcissus_12 小时前
排序算法总结表格
c语言·数据结构·c++·笔记·算法·排序算法·总结
用户83562907805112 小时前
使用 Python 查找和替换 Word 文档中的文本
后端·python
黑马水牛12 小时前
Carla仿真系列:9_Carla 单目障碍物测距,四种方法原理与实测
经验分享·python·深度学习·计算机视觉·ros·传感器·carla仿真
一只小小的芙厨13 小时前
前缀和与差分
数据结构·算法
Python私教13 小时前
多个项目怎么安全合并?适配层、双轨验证与可回滚切换
python·软件架构·系统迁移
船厂电气自动化ai大模型13 小时前
AI大模型与数学第42课:泰勒级数完整展开(神经网络近似核心)
人工智能·python·深度学习·算法·机器学习
从琳开始98913 小时前
优选算法——双指针(算法原理+力扣题)
算法·leetcode·职场和发展
从琳开始98913 小时前
优选算法——滑动窗口(概念+解题模板+LeetCode例题讲解)
算法·leetcode·职场和发展
Nil20813 小时前
leetcode 94二叉树的中序遍历
算法·leetcode·职场和发展