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
相关推荐
凌冰_5 小时前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
Pniubi5 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
戴·菲瑜5 小时前
为什么PPO难以做出顶级棋类引擎
算法·博弈论·rl·ppo
wuyk5556 小时前
Python办公自动化-第01讲-环境搭建与自动化认知
python·自动化·pyqt
高洁016 小时前
数字孪生与计算机视觉:让机器看懂现场
人工智能·python·机器学习·transformer·迁移学习
ComPDFKit7 小时前
RAG 回答只显示 PDF 文件名?用 Python 保留引用页码
开发语言·python·pdf·rag
在所不辞兄8 小时前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
yz_aiks8 小时前
Termux 使用教程:把安卓手机变成随身 Linux(装 Python、SSH 远程、跑自动化脚本)
android·linux·python·智能手机·ssh·termux
2601_9679801110 小时前
Flask Web 应用
python·flask·web开发·环境变量·虚拟环境
aifannihao10 小时前
ß 大写变 SS:用 Python 算清 Ruby2Shell 的缓冲区账本
python·安全·标准库·缓冲区溢出·字符串编码