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
相关推荐
Mryan20052 分钟前
基于 Nao 机器人的摄像头和声呐结合寻路方式
python·机器人·nao 机器人·naoqi
Salt_07283 分钟前
DAY 37 MLP 神经网络的训练
人工智能·python·深度学习·神经网络·机器学习
东方佑6 分钟前
使用Python实现Word文档与JSON格式双向转换:完整教程与代码解析
python·json·word
三斗米11 分钟前
mac系统查看所有安装的Python版本
python
信看12 分钟前
树莓派CAN(FD) 测试
开发语言·python
LYFlied23 分钟前
【每日算法】LeetCode 739. 每日温度:从暴力遍历到单调栈的优雅解决
前端·算法·leetcode·面试·职场和发展
yaoh.wang25 分钟前
力扣(LeetCode) 67: 二进制求和 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
夏鹏今天学习了吗32 分钟前
【LeetCode热题100(74/100)】跳跃游戏
算法·leetcode·游戏
电饭叔37 分钟前
自定义重载运算符--《python语言程序设计》2018版--第8章20题使用Rational类求和数列之一
开发语言·python
Evan芙40 分钟前
基于Nginx和Python的动态站点安装配置
数据库·python·nginx