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
相关推荐
Csvn15 小时前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
小O的算法实验室15 小时前
2026年ASOC,基于深度强化学习的无人机三维复杂环境分层自适应导航规划方法,深度解析+性能实测
算法·无人机·论文复现·智能算法·智能算法改进
cch891816 小时前
Python主流框架全解析
开发语言·python
sg_knight16 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财16 小时前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張40816 小时前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_4235339916 小时前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
郭涤生16 小时前
STL vector 扩容机制与自定义内存分配器设计分析
c++·算法
༾冬瓜大侠༿16 小时前
vector
c语言·开发语言·数据结构·c++·算法
Ricky111zzz16 小时前
leetcode学python记录1
python·算法·leetcode·职场和发展