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
相关推荐
会编程的土豆2 分钟前
【日常做题】 代码随想录(岛屿最大面积+寻宝)
数据结构·算法·图论
大佬王8 分钟前
WebSocket 连接池生产级实现:实时行情高可用与负载均衡
python·架构
阿洛学长8 分钟前
汉洛塔结构思维
算法
木子n115 分钟前
第2篇:坐标变换与数学基础:FOC算法的核心数学工具
算法·电机控制·foc
阿Y加油吧28 分钟前
两道经典 DP 题:零钱兑换 & 单词拆分(完全背包 + 字符串 DP)
算法
疯狂打码的少年36 分钟前
有序线性表删除一个元素:顺序存储 vs 单链表,平均要移动多少个元素?
数据结构·算法·链表
ronindong37 分钟前
Cursor 插件分享 | md-couture:一键将 Markdown 转换成带精美样式的 HTML
人工智能·python·ai编程
智慧地球(AI·Earth)37 分钟前
规则引擎实战:Python中re库和pyknow库规则引擎实战教程
开发语言·python·程序人生
y = xⁿ1 小时前
20天速通LeetCode day07:前缀和
数据结构·算法·leetcode
是小蟹呀^1 小时前
【总结】LangChain中的中间件Middleware
python·中间件·langchain·agent