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
相关推荐
高一学习c++会秃头吗几秒前
操作系统内存块分配算法
算法
tang777891 分钟前
2026代理IP选型逻辑与成本控制:动态IP VS 静态IP、住宅IP VS 运营商IP VS 数据中心IP的深入解析
爬虫·python·代理ip·住宅ip·住宅代理·运营商ip
洛水水2 分钟前
【力扣100题】57.合并区间
算法·leetcode
玉树临风ives3 分钟前
atcoder ABC 458 题解
数据结构·c++·算法
如竟没有火炬12 分钟前
有序矩阵中第K小的元素
数据结构·线性代数·算法·leetcode·矩阵·深度优先
叁散13 分钟前
ESP32智能闹钟系统实验报告
单片机·嵌入式硬件·算法
AI玫瑰助手22 分钟前
Python函数:def定义函数与参数传递基础
android·开发语言·python
24kmaigc25 分钟前
NewStarCTF2025-ssti在哪里?-ssrf与ssti注入
python·网络安全·flask·web
Realdagongzai29 分钟前
Linux 6.19.10 内核调度器算法详解
linux·学习·算法·spring·kernel
老虎海子37 分钟前
从零手搓一个 AI 编程助手:Mini Claude Code 完全指南
人工智能·git·vscode·python·github