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
相关推荐
@陈小鱼28 分钟前
MATLAB+Python:基于小样本卷积神经网络的 PPG 血压预测
人工智能·python·机器学习·matlab·脉搏波·血压·一维卷积神经网络
卷无止境35 分钟前
Python数据进阶专题:用声明式验证让数据管道告别"惊喜"
后端·python·数据分析
码云骑士1 小时前
61-LangChain-vs-LlamaIndex-选型对比-功能矩阵-混用实践
python·线性代数·矩阵·langchain
阿豪只会阿巴1 小时前
两小时快速入门 FastAPI--第一回
开发语言·python·fastapi
Hesionberger1 小时前
动态规划与二分法破解最长递增子序列
java·数据结构·python·算法·leetcode
JustNow_Man1 小时前
【Claude Code】 中给 Python + XML 项目建立可靠验证体系
xml·linux·python
薛定猫AI1 小时前
【技术干货】多模型AI编程代理实战:用Python统一接入Claude Opus 4.8
人工智能·python·ai编程
二宝哥2 小时前
08.Python流程控制详解:从基础到实践
开发语言·python
令狐掌门2 小时前
2026华为OD面试题020:日志文件异常检测
算法·leetcode·华为od
To_OC11 小时前
LC 17 电话号码的字母组合:我的回溯算法,就是从这道题开窍的
javascript·算法·leetcode