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
相关推荐
江畔柳前堤7 分钟前
PyQt学习系列11-综合项目:多语言文件管理器
开发语言·网络·python·学习·django·pyqt
眠修15 分钟前
Python 实现web请求与响应
开发语言·python
ThE.wHIte.16 分钟前
leetcode 3068. 最大节点价值之和
算法·leetcode·职场和发展
鸡鸭扣22 分钟前
leetcode hot100:十四、解题思路大全:真·大全!
数据结构·python·算法·leetcode·力扣·笔试
钢铁男儿1 小时前
C# 深入理解类(析构函数和this关键字)
java·python·c#
折戟不必沉沙1 小时前
python使用pycharm和conda 设置默认使用清华镜像
python·pycharm·conda
(・Д・)ノ1 小时前
python打卡day34
开发语言·python
二九筒1 小时前
Python Selenium 使用指南
开发语言·python·selenium
小韩加油呀2 小时前
python定时删除指定索引
python·elk·indics
学技术的大胜嗷2 小时前
YOLOv8损失函数代码详解(示例展示数据变换过程)
人工智能·python·深度学习·yolo·目标检测