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
相关推荐
瞎某某Blinder17 小时前
DFT学习记录[3]:material project api使用方法 mp_api调取与pymatgen保存
java·笔记·python·学习
闲云一鹤18 小时前
UV 包管理器 - 新一代的 Python 包和环境管理神器
前端·python
TracyCoder12318 小时前
LeetCode Hot100(46/100)——74. 搜索二维矩阵
算法·leetcode·矩阵
im_AMBER18 小时前
Leetcode 119 二叉树展开为链表 | 路径总和
数据结构·学习·算法·leetcode·二叉树
DN202018 小时前
当AI开始评估客户的“成交指数”
数据结构·人工智能·python·microsoft·链表
小小张说故事18 小时前
Python图像处理利器:Pillow (PIL)入门指南
后端·python·图像识别
好家伙VCC19 小时前
**标题:发散创新|用Python构建GAN图像生成器:从理论到实战全流程解析**---在深度学习飞速发展的今天,**生成对抗
java·python·深度学习·生成对抗网络
苏荷水19 小时前
万字总结LeetCode100(持续更新...)
java·算法·leetcode·职场和发展