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 小时前
LeetCode2981~3000题目解析
java·leetcode
黑客笔记4 小时前
python小工具win7翻车事故现场
python
岁月宁静7 小时前
从零拆解 AI 语音模拟面试系统
人工智能·python·agent
benchmark_cc7 小时前
个人开发者接入五档盘口:用 QuantDash 读取单只股票的验收清单与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
ZhengEnCi8 小时前
项目越写越乱?先别改架构:用一次目录重排 + 一份可复算的体检脚本把乱治住
python·架构·ai编程
Dmz丶9 小时前
前端转 AI 100 天 Day 45:阶段复盘——从“会调 API”到“做出 AI 产品”
python
Sakura_j_h_9 小时前
MCP SDK 2.0 实战:用 MCPServer 搭本地笔记检索服务
开发语言·笔记·python·qt·ai工具·mcp·mcpserver
QuZhengRong10 小时前
【AI】Agent 全栈进阶|AgentScope 沙箱源码解析
python·学习·ai·agent·沙箱
Eider199810 小时前
Python基础语法之并发相关3
开发语言·python
文丑颜不良啊10 小时前
LeetCode3001~3020题目解析
java·leetcode