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
相关推荐
Swift社区6 分钟前
LeetCode 378 - 有序矩阵中第 K 小的元素
算法·leetcode·矩阵
阿拉丁的梦7 分钟前
【maxscript】矩阵对齐-武器残影
python·3dsmax
mortimer9 分钟前
Python 异常处理进阶:从 `traceback` 细节到稳健的多语言处理器
python
墨染点香9 分钟前
LeetCode 刷题【73. 矩阵置零】
算法·leetcode·矩阵
林木辛24 分钟前
LeetCode热题 438.找到字符中所有字母异位词 (滑动窗口)
算法·leetcode
和鲸社区27 分钟前
四大经典案例,入门AI算法应用,含分类、回归与特征工程|2025人工智能实训季初阶赛
人工智能·python·深度学习·算法·机器学习·分类·回归
dragoooon341 小时前
[优选算法专题二——NO.16最小覆盖子串]
c++·算法·leetcode·学习方法
piaopiaolanghua1 小时前
PyCharm旧版本下载地址
ide·python·pycharm
云天徽上1 小时前
【数据可视化-111】93大阅兵后的军费开支情况———2024年全球军费开支分析:用Python和Pyecharts打造炫酷可视化大屏
开发语言·python·信息可视化·pyecharts