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
相关推荐
Mortalbreeze1 分钟前
深入 Linux 线程机制(三):线程互斥——竞争条件与互斥锁的本质
linux·运维·服务器·c++·算法
江华森2 分钟前
Python 编程快速上手:让繁琐工作自动化 —— 19章全实战笔记
笔记·python·自动化
Mr_Controll3 分钟前
【运动控制——电子凸轮曲线设计(多项式)】
算法·自动化
子豪-中国机器人7 分钟前
第一部分:初赛选择题(30 题,对应线上每日问答)
python
Sam09278 分钟前
【AI 算法精讲 15】余弦相似度:向量检索与归一化内积
人工智能·python·算法·ai
黎阳之光27 分钟前
黎阳之光实时三维重构:重构智慧铁路全新管控范式
大数据·人工智能·物联网·算法·数字孪生
m0_5474866627 分钟前
南京林业大学《线性代数A》期末试卷及答案16-19 23-24学年PDF
线性代数
weixin_4000056031 分钟前
Vision-Language-Action:LMDrive项目架构与核心算法组件
人工智能·深度学习·算法·机器学习·架构·自动驾驶
Starry-sky(jing)31 分钟前
RecursionError: maximum recursion depth exceeded —— 你的函数调用链,踩穿了 CPython 的安全气囊
python·cpython·pydantic·recursionerror·递归深度·递归限制·sys.setrecursionlimit
mingo_敏34 分钟前
强化学习(RL):原理、算法、RLHF落地全解析
人工智能·算法·机器学习