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
相关推荐
STLearner2 小时前
ICML 2026 | LLM×Graph论文总结[2]【Graph4LLM,Graph4Agent,智能体记忆(Memory)
大数据·人工智能·python·深度学习·学习·机器学习·数据挖掘
m沐沐9 小时前
【深度学习】YOLOv2目标检测算法——改进点、网络结构与聚类先验框解析
人工智能·pytorch·深度学习·算法·yolo·目标检测·transformer
不会就选b9 小时前
算法日常・每日刷题--<链表>3
数据结构·算法·链表
geovindu10 小时前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
郭老二11 小时前
【Python】基本语法:装饰器语法糖@
python
Zachery Pole12 小时前
CCF-CSP备战NO.7【队列】
算法
闪电悠米12 小时前
力扣hot100-48.旋转图像-转置翻转详解
算法·leetcode·职场和发展
_Jimmy_12 小时前
Agent常用检索器的详细介绍
python·langchain
满天星830357712 小时前
【算法】最长递增子序列(三种解法)
算法
小柯南敲键盘12 小时前
图片翻译API接入与自动化实现指南
运维·python·自动化