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
相关推荐
XX風2 分钟前
3.2K-means
人工智能·算法·kmeans
可触的未来,发芽的智生2 分钟前
发现:认知的普适节律 发现思维的8次迭代量子
javascript·python·神经网络·程序人生·自然语言处理
真智AI38 分钟前
用 LLM 辅助生成可跑的 Python 单元测试:pytest + coverage 覆盖率报告(含运行指令与排坑)
python·单元测试·pytest
蒟蒻的贤1 小时前
leetcode链表
算法·leetcode·链表
0思必得01 小时前
[Web自动化] Selenium处理文件上传和下载
前端·爬虫·python·selenium·自动化·web自动化
Funny_AI_LAB1 小时前
AI Agent最新重磅综述:迈向高效智能体,记忆、工具学习和规划综述
人工智能·学习·算法·语言模型·agi
Hui Baby1 小时前
Java SPI 与 Spring SPI
java·python·spring
执着2591 小时前
力扣hot100 - 94、二叉树的中序遍历
数据结构·算法·leetcode
-dzk-1 小时前
【代码随想录】LC 707.设计链表
数据结构·c++·算法·链表
小猪咪piggy1 小时前
【Python】(3) 函数
开发语言·python