Python | Leetcode Python题解之第329题矩阵中的最长递增路径

题目:

题解:

python 复制代码
class Solution:

    DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        if not matrix:
            return 0
        
        rows, columns = len(matrix), len(matrix[0])
        outdegrees = [[0] * columns for _ in range(rows)]
        queue = collections.deque()
        for i in range(rows):
            for j in range(columns):
                for dx, dy in Solution.DIRS:
                    newRow, newColumn = i + dx, j + dy
                    if 0 <= newRow < rows and 0 <= newColumn < columns and matrix[newRow][newColumn] > matrix[i][j]:
                        outdegrees[i][j] += 1
                if outdegrees[i][j] == 0:
                    queue.append((i, j))

        ans = 0
        while queue:
            ans += 1
            size = len(queue)
            for _ in range(size):
                row, column = queue.popleft()
                for dx, dy in Solution.DIRS:
                    newRow, newColumn = row + dx, column + dy
                    if 0 <= newRow < rows and 0 <= newColumn < columns and matrix[newRow][newColumn] < matrix[row][column]:
                        outdegrees[newRow][newColumn] -= 1
                        if outdegrees[newRow][newColumn] == 0:
                            queue.append((newRow, newColumn))
        
        return ans
相关推荐
小刘在重生~1 小时前
Java常用类|String类详解 + BigDecimal精准计算(含面试题)
java·开发语言·python
大汉堡玩测试2 小时前
langfuse测试实战(一): 配置一个简单的项目快速落地
python·测试工具
一位正在转型AI全栈的前端工程师2 小时前
AI 全栈学习之旅 -Week 8:从单 Agent 到多 Agent 协作:LangGraph 实战与记忆持久化
前端·python
长江后浪博客2 小时前
Python + YOLOv8 疲劳驾驶 AI 视觉检测入门:从模型训练到 ONNX 实时摄像头检测完整实战
人工智能·python·yolo·疲劳驾驶检测·onnx·yolov8
hhzz2 小时前
【OpenCV 入门到精通 01】认识 OpenCV 与计算机视觉:从零建立全局认知
人工智能·python·opencv·计算机视觉·开源
一马平川的大草原3 小时前
如何实现SVG转Mermaid图
python·svg·格式转换·mermaid
PFFstronger3 小时前
基于 Dify 知识库 + Ollama 大模型,自动生成测试用例并导出 XMind 的完整方案
人工智能·python·测试用例·xmind
SomeBottle3 小时前
【小记】图片托管从又拍云迁移到腾讯云 EO + COS(兼容图片处理参数)
python·计算机网络·学习笔记·对象存储·cdn·折腾
cts6184 小时前
FDE架构师前端选型指南
python
2601_962293795 小时前
【Python教程:自动化处理文件】
python·自动化·编程·文件处理·os模块