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
相关推荐
xingzhemengyou11 分钟前
Python GUI中常用的after
开发语言·python
郝学胜-神的一滴13 分钟前
Python抽象基类与abc模块详解:优雅设计接口的利器
开发语言·python·程序人生
小南知更鸟19 分钟前
前端静态项目快速启动:python -m http.server 4173 与 npx serve . 全解析
前端·python·http
小钟不想敲代码24 分钟前
Python(三)
java·python·servlet
皮卡兵快跑1 小时前
小试牛刀-基于几何要素分辨insar升降轨道数据
python·arcpy
j .1 小时前
Java 集合的核心概念笔记
开发语言·python
qq_430855881 小时前
线代第五章线性方程组第五节:矩阵的对角化
线性代数·矩阵
宸津-代码粉碎机1 小时前
Spring 6.0+Boot 3.0实战避坑全指南:5大类高频问题与解决方案(附代码示例)
java·数据仓库·hive·hadoop·python·技术文档编写
傻啦嘿哟1 小时前
Python自动整理音乐文件:按艺术家和专辑分类歌曲
数据库·python·分类
weixin_462446231 小时前
基于 Flask + lunar-python 的农历转换 API 实战(公历 ↔ 农历 / 干支 / 生肖 / 节日)
python·flask·节日