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
相关推荐
青少儿编程课堂13 分钟前
背包问题(0/1 背包与完全背包)解题精讲——动态规划入门
c++·python·算法·bfs·信息学竞赛
code2cat26 分钟前
【随笔】MCP工具注解的信任边界:四个提示如何参与调用决策
python·ai agent·mcp
慢云智慧空间29 分钟前
从设备智能到空间理解,慢云科技如何重新定义智慧建筑
python·科技
浮链序30 分钟前
用 Claude Haiku 5.5 做子智能体路由,把 Agent 成本砍掉六成
人工智能·python·llm
冯一川35 分钟前
安装Pyside 6
python
光影少年40 分钟前
为什么 JavaScript 中 0.1 + 0.2 !== 0.3,如何让其相等?
前端·javascript·算法
HEJOO91 小时前
Linux 设备驱动系列——使用全局工作队列
java·linux·算法
Code_Solitude1 小时前
c语言:递归
java·c语言·算法
估值探索者1 小时前
【Python量化系统工程实战 #08】从脚本到生产:量化系统上线 checklist 的最小闭环
java·开发语言·jvm·python·数据挖掘·数据·股票数据api接口
李可以量化1 小时前
如何开通基于 AI 打造的 A 股量化策略(下):特征工程与大模型决策落地
python