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
相关推荐
λqaq73 分钟前
Redis 数据库基础:安装、5 大核心数据类型与常用命令
linux·数据库·redis·python·缓存
BioRunYiXue3 分钟前
科研干货 | IC50全面解读:概念解析、实验设计与数据分析要点
java·开发语言·javascript·人工智能·算法·数据挖掘·数据分析
hahaha60163 分钟前
HLS高层次综合设计技巧--UART_TX接收模块设计案例
人工智能·算法·计算机视觉
天天被压力5 分钟前
【零依赖量化数据实战 #31】沪深A实时盘口全景:逐笔·全盘实时·最新价·历史逐笔
java·人工智能·python
302wanger7 分钟前
一个程序员看完《逆行人生》:电影没说透的,比电影更扎心
算法
hele_two8 分钟前
C++模拟蚁群(二)
c++·算法·数学建模·图形渲染
WK100%12 分钟前
LeetCode双题:滑动窗口破解最小子数组
c++·经验分享·笔记·算法
sheeta199813 分钟前
LeetCode 每日一题笔记 日期:2026.09.02 题目:3875.构造奇偶一致的数组 I
笔记·算法·leetcode
明月_清风22 分钟前
递归算法:从原理到实战,一次讲透
后端·算法·go
CYLAM202527 分钟前
STC32G12K128单片机实现高精度算法及常用初等函数值的计算
算法