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美赛赛题初步翻译F题】2026_ICM_Problem_F
大数据·c语言·python·数学建模·matlab
A_nanda8 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
小鸡吃米…9 小时前
机器学习中的代价函数
人工智能·python·机器学习
Li emily10 小时前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股
代码雕刻家10 小时前
2.4.蓝桥杯-分巧克力
算法·蓝桥杯
m0_5613596710 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
Ulyanov10 小时前
顶层设计——单脉冲雷达仿真器的灵魂蓝图
python·算法·pyside·仿真系统·单脉冲
2401_8384725111 小时前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
CoLiuRs11 小时前
语义搜索系统原理与实现
redis·python·向量·es
zhihuaba11 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python