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
相关推荐
手写码匠2 分钟前
从零实现大模型推理引擎:Continuous Batching 与动态调度系统深度解析
人工智能·深度学习·算法·aigc
俺不中嘞12 分钟前
python常用函数
开发语言·python
wabs66623 分钟前
关于单调栈【力扣503.下一个更大元素II的思考】
算法·单调栈
薛定猫AI24 分钟前
【技术干货】大模型文档结构化提取实战:Python解析PDF发票并批量生成CSV
java·python·pdf
c2385627 分钟前
下篇:伸缩魔法!进阶吃透可变滑动窗口篇
c++·算法
186******2053130 分钟前
RuView 新手快速上手与实战指南
算法
zhiSiBuYu051731 分钟前
RAG 性能优化与缓存策略实战指南
人工智能·python·机器学习
txzrxz32 分钟前
关于二维/多维前缀和
算法
来一碗刘肉面37 分钟前
顺序表的按值查找
数据结构·c++·算法
荣码40 分钟前
Prompt工程实战:同一个需求换3种写法,效果差10倍
java·python