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
相关推荐
飞Link7 小时前
什么是 AirSim?一文读懂无人机仿真平台
python·算法·无人机
曲径海盗7 小时前
【Python 学习第 38 天】for 循环
python·学习笔记·编程入门
在世修行7 小时前
智学文枢:变式题生成引擎
python·ai·pyside·题目生成
一去不复返的通信er9 小时前
贪心算法-合并区间(LeetCode 56)
算法·leetcode·贪心算法
On The Road :9 小时前
Java 多线程详解:从入门到线程安全
java·python·安全
岁月宁静9 小时前
如何设计支持 Skills 的 Agent?一套可扩展的四层架构
python·agent
Shaoshing9 小时前
LeetCode100 49. 字母异位词分组
java·算法
岁月宁静10 小时前
CrewAI 快速上手:10 分钟搭建你的第一个 Agent 团队
python·agent
YFJ_mily10 小时前
第二届区块链技术与基础模型国际学术会议(BTFM2027)
算法·区块链·能源·智能系统·rdlink研发家·机器人自动化