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 分钟前
【K-Means深度探索(一)】数据炼金术第一步:从零手撕K-Means聚类算法
算法·kmeans·聚类
像风一样自由20201 分钟前
XGBoost、LightGBM、CatBoost 原理深度剖析与全面对比
python
我想回家种地3 分钟前
算法期末复习
算法
用户230826676657 分钟前
Python的管道符(|)联合类型语法糖
python
东木月12 分钟前
使用python获取Windows产品标签
开发语言·windows·python
AIFQuant15 分钟前
2026 越南证券交易所(VN30, HOSE)API 接口指南
大数据·后端·python·金融·restful
rgeshfgreh21 分钟前
MPPI算法实战:运动规划新利器
算法
Xの哲學23 分钟前
Linux epoll 深度剖析: 从设计哲学到底层实现
linux·服务器·网络·算法·边缘计算
dagouaofei26 分钟前
AI 生成 2026 年工作计划 PPT,模板与结构能力对比
人工智能·python·powerpoint
木头左27 分钟前
波动率期限结构调整策略在指数期权日历价差中的应用研究
python