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 分钟前
使用@property将类方法包装为属性
开发语言·python
_日拱一卒30 分钟前
LeetCode:滑动窗口的最大值
数据结构·算法·leetcode
福运常在1 小时前
股票数据API(19)次新股池数据
java·python·maven
多看书少吃饭1 小时前
Vue3 + Java + Python 打造企业级大模型知识库(含 SSE 流式对话完整源码)
java·python·状态模式
mifengxing1 小时前
力扣HOT100——(1)两数之和
java·数据结构·算法·leetcode·hot100
Z.风止1 小时前
Large Model-learning(2)
开发语言·笔记·python·leetcode
蓝天守卫者联盟11 小时前
玩具喷涂废气治理厂家:行业现状、技术路径与选型指南
大数据·运维·人工智能·python
m0_738120721 小时前
我的创作纪念日0328
java·网络·windows·python·web安全·php
red1giant_star1 小时前
浅析文件类漏洞原理与分类——含payload合集与检测与防护思路
python·安全
tryCbest2 小时前
Python之Flask开发框架(第一篇) — 从安装到第一个应用
开发语言·python·flask