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
相关推荐
love530love2 分钟前
ComfyUI Hunyuan-3D-2 插件安装问题解决方案
人工智能·windows·python·3d·comfyui·hunyuan-3d-2·pygit2
ldccorpora3 分钟前
GALE Phase 1 Chinese Broadcast News Parallel Text - Part 1数据集介绍,官网编号LDC2007T23
人工智能·深度学习·算法·机器学习·自然语言处理
千金裘换酒7 分钟前
LeetCode 数组经典题刷题
算法·leetcode·职场和发展
我是一只小青蛙88821 分钟前
Python Pandas 从入门到精通全指南
python
fie88891 小时前
MATLAB有限元框架程序
python·算法·matlab
小郭团队1 小时前
1_5_五段式SVPWM (传统算法反正切+DPWM1)算法理论与 MATLAB 实现详解
人工智能·嵌入式硬件·算法·dsp开发
我是小疯子661 小时前
Python3.11.4离线安装PyInstaller全攻略
python
思成Codes1 小时前
ACM训练:接雨水3.0——动态接雨水
数据结构·算法
alphaTao1 小时前
LeetCode 每日一题 2026/1/12-2026/1/18
python·算法·leetcode
sin_hielo1 小时前
leetcode 2943
数据结构·算法·leetcode