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
相关推荐
YXXY313几秒前
二分查找算法
算法
爱玩亚索的程序员1 分钟前
算法入门(一)Python基础(list、dict、set、tuple、for、enumerate、lambda、sorted)
python·算法·list
一叶落4381 分钟前
LeetCode 134. 加油站(贪心算法详解 + C语言实现)
c语言·数据结构·算法·leetcode·贪心算法
say_fall2 分钟前
位运算底层逻辑与解题应用绪论
c++·学习·算法·leetcode·职场和发展
熙金顺乐葵攘3 分钟前
Web2py Grid 组件实现主从双表联查,卡片订单UI展现、全字段搜索导出的改造
python·web2py
陌雨’5 分钟前
提取b站视频的ai字幕
爬虫·python
Σίσυφος19007 分钟前
为什么 Generalized ICP(GICP)通常比 Point-to-Plane 更稳定?
算法
weipt13 分钟前
FBX转3DTiles带坐标的高效转换工具
python
j_xxx404_17 分钟前
常见位运算基础知识,技巧总结以及力扣实战
数据结构·c++·算法·leetcode
RuiBo_Qiu22 分钟前
【LLM进阶-后训练&部署】1. 大语言模型全参数微调:从前向推理到反向传播的底层原理解析
人工智能·算法·语言模型·自然语言处理·ai-native