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
相关推荐
花酒锄作田6 小时前
企业微信机器人与 DeepAgents 集成实践
python·mcp·deepagents
likerhood8 小时前
java中`==`和`.equals()`区别
java·开发语言·python
IronMurphy8 小时前
【算法三十九】994. 腐烂的橘子
算法
qq_283720059 小时前
Python Celery + FastAPI + Vue 全栈异步任务实战
vue.js·python·fastapi
2401_885885049 小时前
营销推广短信接口集成:结合营销策略实现的API接口动态变量填充方案
前端·python
Ares-Wang10 小时前
算法》》旅行商问题 TSP、7座桥问题 哈密顿回路 深度优先 和 宽度优先
算法·深度优先·宽度优先
Liqiuyue10 小时前
Transformer:现代AI革命背后的核心模型
人工智能·算法·机器学习
WolfGang00732110 小时前
代码随想录算法训练营 Day34 | 动态规划 part07
算法·动态规划
telllong10 小时前
Python异步编程从入门到不懵:asyncio实战踩坑7连发
开发语言·python
Kk.080210 小时前
Linux(十一)fork实例练习、文件操作示例及相关面试题目分享
linux·运维·算法