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 分钟前
Python 教程:我们可以给 Python 文件起中文名吗?
开发语言·python
豌豆花下猫19 分钟前
Python 潮流周刊#99:如何在生产环境中运行 Python?(摘要)
后端·python·ai
爱研究的小陈19 分钟前
Day 3:数学基础回顾——线性代数与概率论在AI中的核心作用
算法
渭雨轻尘_学习计算机ing21 分钟前
二叉树的最大宽度计算
算法·面试
小杨40422 分钟前
python入门系列二十(peewee)
人工智能·python·pycharm
弧襪22 分钟前
FlaskRestfulAPI接口的初步认识
python·flaskrestfulapi
船长@Quant24 分钟前
文档构建:Sphinx全面使用指南 — 进阶篇
python·markdown·sphinx·文档构建
cloudy49127 分钟前
强化学习:历史基金净产值,学习最大化长期收益
python·强化学习
Bruce_Liuxiaowei39 分钟前
使用Python脚本在Mac上彻底清除Chrome浏览历史:开发实战与隐私保护指南
chrome·python·macos
ruyingcai6666661 小时前
用python进行OCR识别
开发语言·python·ocr