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
相关推荐
im_AMBER13 分钟前
Leetcode 65 固定长度窗口 | 中心辐射型固定窗口
笔记·学习·算法·leetcode
Python极客之家16 分钟前
基于数据挖掘的微博情感分析及话题追踪系统
python·数据挖掘·毕业设计·课程设计·情感分析
kwg12620 分钟前
Dify二次开发构建api后端Docker离线镜像方案
服务器·人工智能·python
a***131425 分钟前
【玩转全栈】----Django制作部门管理页面
后端·python·django
杨超越luckly34 分钟前
Python应用指南:利用高德地图采集AOI数据
python·arcgis·高德地图·数据可视化·aoi数据
梁正雄41 分钟前
5、python 模块与包
linux·服务器·python
I_ltt_Itw,42 分钟前
Python协程学习笔记
开发语言·网络·python
爱笑的眼睛111 小时前
Flask应用API深度开发:从单体架构到微服务设计模式
java·人工智能·python·ai
AI小云1 小时前
【数据操作与可视化】Matplotlib绘图-常用操作
python·数据可视化
资深web全栈开发1 小时前
[特殊字符] LeetCode 2141:如何让 N 台电脑续航最久?——“二分答案“套路一文讲透
算法·leetcode