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
相关推荐
小小测试开发4 分钟前
pytest 库用法示例:Python 测试框架的高效实践
开发语言·python·pytest
至善迎风21 分钟前
把 Python 应用打包成 Mac 应用程序 — 完整指南
python·macos
应用市场1 小时前
无人机编队飞行原理与Python仿真实现完整指南
python·无人机·cocos2d
蓝桉~MLGT2 小时前
Python学习历程——字符串相关操作及正则表达式
python·学习·正则表达式
一晌小贪欢2 小时前
Python爬虫第5课:正则表达式与数据清洗技术
爬虫·python·正则表达式·网络爬虫·python爬虫·python3·网页爬虫
Nina_7172 小时前
Google提示词白皮书总结(2)
人工智能·python
Lynnxiaowen2 小时前
今天我们继续学习python3编程之python基础
linux·运维·python·学习
hui函数3 小时前
Python全栈(基础篇)——Day10:后端内容(map+reduce+filter+sorted+实战演示+每日一题)
后端·python
hui函数3 小时前
Python全栈(基础篇)——Day13:后端内容(模块详解)
后端·python