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
相关推荐
小趴蔡ha6 小时前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
2401_868534786 小时前
RTOS之RT-Thread & Linux:线程/进程管理与调度核心差异分析
c++·python
wabs6667 小时前
关于图论【卡码网117.软件构建的思考】
数据结构·算法·软件构建·图论·卡码网
mifengxing7 小时前
LeetCode 41.缺失的第一个正数|Hard题O(n)+O(1)最优解法深度解析
java·算法·leetcode·排序算法
数字化转型分享点滴7 小时前
富士康、蓝思科技为何选择四化信息?MES制造执行系统的实践
python·科技
wling03017 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
魔镜前的帅比7 小时前
(开源项目)x-claw(总)
python·ai·rust·开源
Tongzhi20268 小时前
从部署到运维:通芝科技无感考勤一体机的全流程效率解析
运维·数据结构·科技·算法·贪心算法
Wang's Blog8 小时前
AI Agent白手起家30: 动态示例选择器之根据长度选择 Few Shot 示例
算法
xrandzj8 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python