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
相关推荐
彳亍1012 分钟前
实现倒计时数字在到达1后自动隐藏(2为最后可见数字),同时继续运行至-1再终止
jvm·数据库·python
X566122 分钟前
CSS如何处理SSR中CSS引入_在服务端渲染时提取关键CSS
jvm·数据库·python
技术小黑1 小时前
CNN算法实战系列03 | DenseNet121算法实战与解析
pytorch·深度学习·算法·cnn
duke8692672141 小时前
PostgreSQL 中高效插入多对多关联数据的三种方案对比与最佳实践
jvm·数据库·python
狮子座明仔1 小时前
AgentSPEX:当 Agent 框架开始把“控制流“从 Python 里抠出来
开发语言·python
m0_463672201 小时前
mysql数据库如何进行逻辑备份与物理备份对比_优缺点分析
jvm·数据库·python
wearegogog1231 小时前
三电平SVPWM逆变器仿真指南
单片机·算法
2401_867623981 小时前
SQL如何进行分组后字符串拼接_使用GROUP_CONCAT或STRING_AGG
jvm·数据库·python
kexnjdcncnxjs1 小时前
MySQL触发器无法触发的原因分析_MySQL触发器排查指南
jvm·数据库·python
Java后端的Ai之路1 小时前
CodeBuddy-Rules配置
人工智能·python·ai编程