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
相关推荐
im_AMBER3 分钟前
手撕hot100之矩阵!看完这篇就AC~
javascript·数据结构·线性代数·算法·leetcode·矩阵
周末也要写八哥3 分钟前
代码中的注释的重要性(二)
开发语言·python
笨笨饿9 分钟前
#79_NOP()嵌入式C语言中内联汇编宏的抽象封装模式研究
linux·c语言·网络·驱动开发·算法·硬件工程·个人开发
XingshiXu17 分钟前
【NWAFU×KUL】不打扰,也能看懂一头牛:非接触式技术正在改变精准畜牧
人工智能·python·深度学习·目标检测·机器学习·计算机视觉·目标跟踪
kybs199117 分钟前
springboot租车系统--附源码68701
java·hadoop·spring boot·python·django·asp.net·php
wxin_VXbishe1 小时前
springboot新能源车充电站管理系统小程序-计算机毕业设计源码29213
java·c++·spring boot·python·spring·django·php
风萧萧19991 小时前
问答样例如何在RAG问答中使用?
算法
好运的阿财1 小时前
OpenClaw工具拆解之memory_search+memory_get
人工智能·python·ai编程·openclaw·openclaw工具
七夜zippoe1 小时前
DolphinDB分区策略:HASH分区与COMPO分区
算法·哈希算法·hash·dolphindb·compo
江南十四行1 小时前
Python生成器与协程:从迭代器到异步编程的进阶之路
开发语言·python