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
相关推荐
顽疲10 分钟前
Java vue 养老系统源码详解:入住核算单 live-check 缴费入账与预交金收据实践
java·vue.js·python·java 养老·springboot 养老·vue养老
Sand(ContextGate)12 分钟前
从开发者调试工具到消费级 App:一个 AI 电商导购项目的 C 端改造与 6 个连环踩坑实录
开发语言·人工智能·python·ai·langchain
_不会dp不改名_14 分钟前
leetcode_3727 最大平方交替和
linux·算法·leetcode
外收内放16 分钟前
数据分析(DataFrame与series)
python·学习·数据分析
信奥卷王21 分钟前
[GESP202509 六级] 货物运输(含视频)
算法
余额瞒着我当琳1 小时前
C++算法学习篇5--二分查找法
c++·学习·算法
Want5951 小时前
Python太极八卦图
开发语言·python
起个名字费劲死了1 小时前
基于灰度/形状的2D模板匹配
算法
川石课堂软件测试1 小时前
自动化测试|持续集成Git使用详解
git·python·jmeter·mysql·ci/cd·容器·kubernetes
杜 硕1 小时前
归并排序详解
数据结构·算法·排序算法