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
相关推荐
❁满城风絮*9 小时前
Claude Code 学习总结
python·agent·claude
维克兜率天11 小时前
【维克】复合型CTA:趋势+套利的双轮驱动
python·学习方法
伞伞悦读11 小时前
【第76期】两张3行表左连接变5行:主键、validate与未匹配排查完整教程
人工智能·python
用户83562907805112 小时前
使用 Python 在 Excel 中添加和自定义迷你图
后端·python
老师我太想进步了202612 小时前
【数据结构-4】算法美学之顺序表
数据结构·算法
用户83562907805112 小时前
使用 Python 在 Excel 图表中添加趋势线与回归方程
后端·python
风影同志7832412 小时前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
特立独行的猫A12 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
UIU11412 小时前
P1481 魔族密码
c++·算法·动态规划
深蓝AI13 小时前
HTTPX 超时 1 秒,接口为何还能跑 2.4 秒?
python