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
相关推荐
6Hzlia1 小时前
【Classic 150 刷题计划】 LeetCode 205. 同构字符串 | C++ 双向绑定与哈希表映射
c++·算法·leetcode
Y幽谷客8 小时前
Python加载本地大模型(Qwen3.5 8B)
python·大模型
伞伞悦读8 小时前
【第36期】Python 目录与路径详解:pathlib、文件遍历、创建、复制、移动和删除风险
开发语言·python
有点。8 小时前
C++03阶段练习(练习题)
数据结构·算法·图论
线上放牧人8 小时前
Windows删除图标缓存
windows·python·pyqt
qq_5470261799 小时前
Python 变量和简单数据类型
python
周末也要写八哥9 小时前
经典算法实例:游戏中弱角色的数量(二)
算法
是Yu欸10 小时前
鸿蒙PC移植:2048 从网页小游戏到 AI 桌面应用
大数据·人工智能·算法·数据挖掘·openharmony·codex
鹿角片ljp10 小时前
KV Cache 解析
java·算法
智搜广告10 小时前
智搜广告:科技行业AI回答优化公司如何破局
大数据·python·elasticsearch·geo