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
相关推荐
bill32822780431 小时前
从 0 到 1 掌握 1688API:商品详情获取技巧
python
hboot8 小时前
AI工程师第五课 - 大语言模型基础
python·llm·fastapi
AOwhisky9 小时前
Python 学习笔记(第一期与第二期)——基础语法——核心知识点自测与详解
开发语言·笔记·python·学习·云原生·运维开发
ysu_03149 小时前
05 | 持久化撤销提示非核心功能
算法·游戏程序
STLearner10 小时前
ICML 2026 | LLM×Graph论文总结[1]【图基础模型,文本属性图,多模态属性图,图对齐,图提示学习,关系深度学习
论文阅读·人工智能·python·深度学习·学习·机器学习·数据挖掘
浮沉98710 小时前
二分查找算法概述&通用模板
算法
习明然11 小时前
我的本地化AI项目(三)
人工智能·python·electron·c#·avalonia
Keven_1111 小时前
算法札记:SPFA判负环算法的证明
算法
什巳11 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode