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
相关推荐
爱读书的小胖1 小时前
LeetCode 122:买卖股票的最佳时机 II(C)解题分析
算法
结局无敌1 小时前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
滴啦嘟啦哒2 小时前
【具身笔记】【π0.5 微调与仿真】五、在MuJoCo中实现可视化仿真
笔记·python·vla·具身
OPEN-F2 小时前
ROS2系列教程:上位机建图与导航(原理综合)
算法·机器人
weixin_307779132 小时前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
全栈练习生2 小时前
AI安全与红队测试
python·ai
tomwang03222 小时前
路径优化建模、优化算法分类及工程化小结
算法·数学建模·分类
小羊没烦恼!2 小时前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
费曼学习法2 小时前
把「发送成功」当「送达」?我排查 IM 长消息被静默吞掉的完整过程
python·ai编程·自动化运维
鸽鸽程序猿2 小时前
【项目】【在线判题系统】b端题目增删改
开发语言·python