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
相关推荐
彦为君4 分钟前
算法思维与经典智力题
java·前端·redis·算法
智能优化与强化学习15 分钟前
Gym(Gymnasium)仿真环境详解(二):环境简介、入门算法、调参要点、核心挑战
算法·强化学习·gym·零基础入门·算法评估
zhanghongyi_cpp16 分钟前
10. 实验书3.4.2 筛选达到预警阈值的病虫害数据
python
mxwin26 分钟前
Unity Shader exp 函数的算法与渲染应用
算法·unity·游戏引擎·shader
tuddy78946427 分钟前
Codex++ 安全边界探秘:从模型能力到风险防御
人工智能·python·安全
“码”力全开33 分钟前
AI视频分析误报优化完整流程
算法·架构·边缘计算
深盾科技_Virbox35 分钟前
深盾科技·Virbox产品体系全景解读:软件安全如何从加密锁走向全生命周期
java·大数据·算法·安全·软件需求
C++、Java和Python的菜鸟44 分钟前
第1章 集合高级
java·jvm·python
梦帮科技1 小时前
UE5 GAS 实战:用 Gameplay Ability System 搭建「赛博修真」境界与技能体系
c++·人工智能·python·ue5·c#
可编程芯片开发1 小时前
基于VSG虚拟同步发电机控制的三相并网逆变器带多组可变负载Simulink建模与仿真
算法