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
相关推荐
We་ct11 分钟前
LeetCode 22. 括号生成:DFS回溯解法详解
前端·数据结构·算法·leetcode·typescript·深度优先·回溯
老师好,我是刘同学14 分钟前
选择排序原理与Python实现
python·排序算法
wmfglpz8824 分钟前
NumPy入门:高性能科学计算的基础
jvm·数据库·python
如若12334 分钟前
WSL2安装Ubuntu完整教程:自定义安装目录到D盘(--location一键搞定)
linux·运维·服务器·pytorch·python·ubuntu·计算机视觉
@fai1 小时前
【Python多线程截图】当 Python 多线程遇上底层 C 库——一次由“串图”引发的线程安全深度思考
python·opencv·numpy
alvin_20051 小时前
python之OpenGL应用(五)变换
python·opengl
深蓝电商API2 小时前
服务器部署爬虫:Supervisor 进程守护
爬虫·python
是梦终空1162 小时前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
竹林8182 小时前
用Python requests搞定Cookie登录,我绕过了三个大坑才成功
爬虫·python·自动化运维
Frostnova丶2 小时前
LeetCode 3296. 使山区高度为零的最少秒数
算法·leetcode