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
相关推荐
SuperEugene6 小时前
Python 异步 async/await:为什么 AI 框架大量使用?| 基础篇
开发语言·人工智能·python
洛水水6 小时前
【力扣100题】14.两数相加
c++·算法·leetcode
我不是小upper6 小时前
相关≠因果!机器学习中皮尔逊相关检验的完整流程
人工智能·算法·机器学习
SMF19196 小时前
【uv】Python包管理器uv安装和应用
开发语言·python·uv
pwn蒸鱼6 小时前
leetcode:21. 合并两个有序链表
算法·leetcode·链表
gergul6 小时前
在llama-cpp-python中使用自己编译的llama.cpp,解决pip install llama-cpp-python报错
python·llama·llama.cpp·llamacpppython
深蓝轨迹6 小时前
#Python零基础机器学习入门教程
人工智能·python·机器学习
洛水水6 小时前
【力扣100题】15.删除链表的倒数第 N 个结点
算法·leetcode·链表
蓝色的杯子6 小时前
Python面试30分钟突击掌握-LeetCode1-Array
开发语言·python·面试
怪祝浙6 小时前
超简洁YOLO8n快速上手人员检测
python