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
相关推荐
XWalnut5 小时前
LeetCode刷题 day29
java·算法·leetcode
VIP_CQCRE5 小时前
用 Ace Data Cloud 快速接入 AI 视频生成:HappyHorse Videos API 实战指南
人工智能·python·api·ai视频生成·acedatacloud
embrace_the_sunhaha5 小时前
卡尔曼滤波理解
算法
叩码以求索6 小时前
使用next数组加速匹配过程
java·数据结构·算法
阿豪只会阿巴6 小时前
两小时快速入门 FastAPI--第二回
windows·python·fastapi
名字还没想好☜6 小时前
Go 内存逃逸分析:什么时候变量跑到堆上
开发语言·算法·性能优化·golang·go·内存逃逸
li星野6 小时前
滑动窗口五题通关:从食堂打饭到上下文窗口——算法与大模型的内存管理哲学
算法
Ivanqhz6 小时前
NFM(神经因子分解机)
开发语言·javascript·人工智能·算法·蓝桥杯
深圳市快瞳科技有限公司6 小时前
从人工录入到秒级识别:保单OCR识别厂家选型指南
人工智能·算法·计算机视觉·ocr
小欣加油6 小时前
leetcode1331 数组序号转换
数据结构·c++·算法·leetcode·职场和发展