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
相关推荐
songroom2 分钟前
python: 扣子工作流创建与dbpystream api 自主插件开发
python
山土成旧客4 分钟前
【Python学习打卡-Day36】实战重构:用PyTorch神经网络升级信贷预测项目
python·学习·重构
27669582926 分钟前
dy x-tt-session-dtrait 逆向分析
python·node·dy·dy逆向·抖音请求头逆向·session-dtrait·dtrait
Croa-vo7 分钟前
Optiver OA 气球节模拟题:拆解系统建模的核心逻辑,附避坑指南
java·数据结构·算法·leetcode·职场和发展
byzh_rc7 分钟前
[数字信号处理-入门] 复频域分析
线性代数·信号处理
小途软件16 分钟前
基于深度学习的驾驶人情绪识别
java·人工智能·pytorch·python·深度学习·语言模型
Kratzdisteln17 分钟前
【MVCD 7】
python·pygame
向量引擎18 分钟前
[架构师级] 压榨GPT-5.2与Sora 2的极限性能:从单体调用到高并发多模态Agent集群的演进之路(附全套Python源码与性能调优方案)
开发语言·人工智能·python·gpt·ai·ai写作·api调用
逻极24 分钟前
数据分析项目:Pandas + SQLAlchemy,从数据库到DataFrame的丝滑实战
python·mysql·数据分析·pandas·sqlalchemy
小白学大数据25 分钟前
Java 异步爬虫高效获取小红书短视频内容
java·开发语言·爬虫·python·音视频