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
相关推荐
普通攻击往后拉11 分钟前
Leetcode 448. 找到所有数组中消失的数字
算法·leetcode·职场和发展
Yolanda_202216 分钟前
Python学习-第九部分-错误处理与异常处理
开发语言·python·学习
mifengxing30 分钟前
LeetCode 189 轮转数组|3种解法拆解,从暴力到O(1)原地最优解
数据结构·算法·leetcode
这个人懒得名字都没写1 小时前
Flask + PyArmor Gunicorn启动报错:RuntimeError: unauthorised use of script
python·flask·gunicorn·pyarmor
C++、Java和Python的菜鸟1 小时前
第10章 后端Web进阶(Maven高级)
开发语言·python
暗黑小白1 小时前
路由策略与引擎可替换性
后端·python·ai agent
小罗水1 小时前
第 20 章 高级 RAG 技术与检索优化
人工智能·python·机器学习
bamb002 小时前
一个项目带你入门AI应用开发06
python
liwulin05062 小时前
【ESP32S3】调用百度云语音合成接口后重启
python
程序员-珍2 小时前
力扣 877. 石子游戏
算法·leetcode·游戏