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
相关推荐
copyer_xyf1 分钟前
Agent MCP
后端·python·agent
闵孚龙2 分钟前
Autograd 自动求导:PyTorch 训练模型的发动机
人工智能·pytorch·python
FL16238631297 分钟前
基于CNN深度学习算实现手写字母识别系统python源码+训练好的模型+说明文档
python·深度学习·cnn
极创信息8 分钟前
信创产品适配测试认证,域名和SSL是必须的吗?
java·开发语言·网络·python·网络协议·ruby·ssl
喵叔哟10 分钟前
第3周学习笔记
python·langchain
码云骑士12 分钟前
11-GIL不是性能杀手(上)-CPU密集vsIO密集的实测对比
开发语言·python
johnny23313 分钟前
Python生态模版引擎:Django、Jinja2、Liquid、Mustache、Mako、Chameleon
python
喵叔哟17 分钟前
Week 3 --Day 5:性能优化与监控
人工智能·python·性能优化·langchain
Kingairy17 分钟前
python3装饰器
开发语言·python
暗黑小白23 分钟前
第八篇:人在回路与内容安全 —— 当 AI 说“让我请示一下“
python·安全·架构·ai agent