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
相关推荐
何以解忧,唯有..3 分钟前
Python 中获取目录操作完全指南
windows·python·microsoft
南京云森杉木桩7 分钟前
常见打桩木品牌推荐,选对材质让工程更稳固
人工智能·python·材质
总有刁民想爱朕ha20 分钟前
Python PyQt5图片批量转MP4视频工具:本地离线免费无水印,完整代码
开发语言·python·qt
zyj88909124 分钟前
濮阳工厂目视化设计安全警示牌材质怎么选耐用
python·安全·材质
宸津-代码粉碎机40 分钟前
FastUtil+AI多Agent实战:Java AI项目性能终极加速方案
java·服务器·开发语言·python·安全·php
for_ever_love__43 分钟前
python基础语法学习: 装饰器
python·学习·装饰器·装饰器模式
Python私教1 小时前
Python 3.15 来了:free-threading 稳定 ABI 能给高并发服务带来什么
开发语言·python
tju新生代魔迷1 小时前
Python学习日记2
python·学习
Zane19942 小时前
create_task 和直接 await 到底有什么不一样?asyncio 的 Task、gather 与并发数量控制
后端·python
李可以量化2 小时前
Redis 从了解到精通(四・下):分区技术原理与选型全解析
python