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
相关推荐
练习时长一年5 分钟前
LeetCode热题100(杨辉三角)
算法·leetcode·职场和发展
Data_agent8 分钟前
Python 编程实战:函数与模块化编程及内置模块探索
开发语言·python
十铭忘10 分钟前
windows系统python开源项目环境配置1
人工智能·python
Generalzy27 分钟前
langchain deepagent框架
人工智能·python·langchain
栈与堆33 分钟前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
万行1 小时前
机器学习&第二章线性回归
人工智能·python·机器学习·线性回归
nervermore9901 小时前
3.3 Python图形编程
python
zhengfei6111 小时前
世界各地免费电视频道的 M3U 播放列表。
python
努力学算法的蒟蒻1 小时前
day58(1.9)——leetcode面试经典150
算法·leetcode·面试
心静财富之门1 小时前
退出 for 循环,break和continue 语句
开发语言·python