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
相关推荐
atunet7 分钟前
关于图算法中的连通分量检测与最小割问题7
算法
兜客互动23 分钟前
2026年AI关键词拓展挖掘软件,高效助力内容创作精准获流
人工智能·python
weixin_5386019724 分钟前
智能体测开Day30pytest测试框架
python
MC皮蛋侠客26 分钟前
uv 系列(七):CI/CD、Docker 与私有索引——生产级交付
python·ci/cd·docker·uv
心运软件34 分钟前
银行客户流失预测(Python 完整实战)
算法
邪神与厨二病39 分钟前
牛客周赛 Round 153
python·算法
yaoxin5211231 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python
groundhappy1 小时前
idalib安装和codex ida-mcp配置
linux·开发语言·python
培之2 小时前
RTX 5090 安装 pytorch3d
人工智能·pytorch·python
Metaphor6922 小时前
使用 Python 在 PowerPoint 中创建折线图和条形图
python·信息可视化·powerpoint·图表