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
相关推荐
To_OC2 小时前
LC 15 三数之和:双指针不难,难的是把去重做对
javascript·算法·leetcode
benchmark_cc3 小时前
如何用 Python + QuantDash 快速构建高胜率“配对交易(Pairs Trading)”策略?
开发语言·人工智能·python·pandas·量化交易·quantdash
renhongxia14 小时前
世界模型,是“空中楼阁”还是AGI的“最后一块拼图”?
运维·服务器·数据库·人工智能·算法·agi
Python+994 小时前
Java 枚举类(Enum)详解:从基础到高级应用
java·开发语言·python
dunge20265 小时前
2026年7月最新ChatGPT Plus / Pro 与 Codex:当 AI Agent 最新5.6版本来袭,必须理解事务、幂等与补偿
开发语言·人工智能·python
zephyr056 小时前
动态规划-最长上升子序列问题
算法·动态规划
闪电悠米7 小时前
力扣hot100-56.合并区间-排序详解
数据结构·算法·leetcode·贪心算法·排序算法
小白学大数据7 小时前
两周完成爬虫技术栈升级:Scrapy 迁移 Crawlo 的路径与取舍
爬虫·python·scrapy
用户8356290780517 小时前
使用 Python 在 Excel 中添加和自定义文本框
后端·python
总裁余(余登武)8 小时前
python多个py文件打包【解决exe不能移动运行bug】
python