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
相关推荐
打工仔折腾 AI1 分钟前
AI Agent 工程化实战(二):5 分钟跑通 Deep Agent 并逐层拆解底层链路
java·数据库·人工智能·后端·python·langchain·ai agent 实战
外收内放3 分钟前
FastAPI猜字谜实战(4):让AI主持人开口
开发语言·python·学习·fastapi
云和数据.ChenGuang3 分钟前
Python map() 函数详解:从语法、原理到实战用法
开发语言·人工智能·python·langchain·1024程序员节
CQU_JIAKE9 分钟前
10.25【A】
数据结构·算法
2601_9628857222 分钟前
baostock vs Tushare:哪个免费股票数据 API 更好用?
python
greencherry_27 分钟前
大连模屿石膏课模具配比全固定,调色浇注之外还缺什么?
算法·生活
hahaha601627 分钟前
数字图像锐化
开发语言·python
xiangjiaodalishi36 分钟前
主流 AI 爬虫 User-Agent 清单大全:分组、配置与持续维护(2026 版)
人工智能·爬虫·python
普贤莲花37 分钟前
先学Workbuddy还是“人工智能训练师”,或者python基础课?
开发语言·人工智能·python
砚底藏山河37 分钟前
python量化实操:回测数据缓存与重放
java·python·金融·1024程序员节