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 学习第 65 天】字典基础
python·学习笔记·编程入门
Wellijohn1 小时前
Docker 瘦身、手写 MCP、异步并发:被问得最多的 12 个问题,一次答完
python·docker·mcp
我叫黑大帅2 小时前
拒绝加字段堆屎山!利用位掩码与流程编排优雅落地 上图下文 复合状态
后端·算法·面试
罗西的思考3 小时前
【轻量化复刻大模型 / KIMI K3】K3 PostTrain 后训练交互式演示
人工智能·算法·机器学习
VW_4044 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
Navigator_Z4 小时前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode
yiangL_4 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
Dmz丶5 小时前
前端转 AI 100 天 Day 52:RAG 项目实战(一)——从零搭建企业知识库
python
电科_银尘5 小时前
【大模型算法与工程 39】PPO:策略比率、裁剪目标与训练稳定性
人工智能·算法·机器学习
shehuiyuelaiyuehao6 小时前
算法68,字符串相乘
算法