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
相关推荐
星空椰8 小时前
Python 面向对象高级:继承与类定义详解
开发语言·python
凯瑟琳.奥古斯特8 小时前
高阶子查询题目精炼
开发语言·数据库·python·职场和发展·数据库开发
风之所往_9 小时前
Python 3.4 新特性全面总结
python
叶小鸡9 小时前
小鸡玩算法-力扣HOT100-多维动态规划
算法·leetcode·动态规划
太阳上的雨天9 小时前
任何格式的文件转Markdown
python·ai
yaoxin52112310 小时前
419. 现代 Java IO 最佳实践 - 写入文本文件
java·windows·python
菜菜的顾清寒10 小时前
力扣HOT100(42)链表-随机链表的复制
算法·leetcode·链表
weixin_4684668510 小时前
纳米 AI 搜索新手极速上手指南
人工智能·python·深度学习·搜索引擎·ai·语言模型·自然语言处理
凯瑟琳.奥古斯特10 小时前
数据库原理选择题精选
数据库·python·职场和发展