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
相关推荐
炽烈小老头8 小时前
【每天学习一点算法 2026/04/11】Pow(x, n)
学习·算法
旖-旎8 小时前
哈希表(存在重复元素)(3)
数据结构·c++·学习·算法·leetcode·散列表
apcipot_rain8 小时前
Python实战——蒙特卡洛模拟分析杀牌游戏技能收益
python·游戏·数学建模
明月醉窗台8 小时前
[jetson] AGX Xavier 安装Ubuntu18.04及jetpack4.5
人工智能·算法·nvidia·cuda·jetson
计算机安禾8 小时前
【数据结构与算法】第39篇:图论(三):最小生成树——Prim算法与Kruskal算法
开发语言·数据结构·c++·算法·排序算法·图论·visual studio code
老绿光8 小时前
Python 字典完全指南:从入门到实战
linux·服务器·python
weixin_513449968 小时前
walk_these_ways项目学习记录第九篇(通过行为多样性 (MoB) 实现地形泛化)--学习算法
学习·算法·机器学习
fish_xk8 小时前
c++内存管理
开发语言·c++·算法
Tisfy8 小时前
LeetCode 3740.三个相等元素之间的最小距离 I:今日先暴力,“明日“再哈希
算法·leetcode·哈希算法·题解·模拟·遍历·暴力
是小蟹呀^8 小时前
【总结】LangChain中如何维持记忆
python·langchain·memory