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
相关推荐
IAUTOMOBILE10 分钟前
Python 流程控制与函数定义:从调试现场到工程实践
java·前端·python
Fuxiao___39 分钟前
C 语言核心知识点讲义(循环 + 函数篇)
算法·c#
漫随流水1 小时前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
TT_44192 小时前
python程序实现图片截图溯源功能
开发语言·python
小陈的进阶之路2 小时前
logging 日志模块笔记
python
cqbelt2 小时前
Python 并发编程实战学习笔记
笔记·python·学习
穿条秋裤到处跑3 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
智算菩萨3 小时前
【论文复现】Applied Intelligence 2025:Auto-PU正例无标签学习的自动化实现与GPT-5.4辅助编程实战
论文阅读·python·gpt·学习·自动化·复现
小陈工4 小时前
2026年3月31日技术资讯洞察:AI智能体安全、异步编程突破与Python运行时演进
开发语言·jvm·数据库·人工智能·python·安全·oracle
老李的勺子4 小时前
Agent 记忆失效的 5 种方式:完整排查复盘
python·llm