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
相关推荐
一位正在转型AI全栈的前端工程师8 分钟前
AI 全栈学习之旅 -Week 5:RAG 知识库问答系统:从零到生产级部署的全栈实践总结
前端·python
2601_9623818611 分钟前
Python办公联动:Excel数据一键自动生成PPT图表
python·数据分析·自动化·excel·ppt
东莞市永盛电气17 分钟前
三相208V变380V变压器,出海工业设备供电适配方案
python·单片机·嵌入式硬件
未若君雅裁1 小时前
上下文压缩双刃剑-Summarization与ContextEditing中间件实战
python·中间件·langchain
IT毕设实战小研1 小时前
电影数据可视化推荐系统
大数据·后端·爬虫·python·算法·信息可视化·课程设计
前端 贾公子2 小时前
第09章:上下文与记忆 (3)
python·langchain
缘友一世2 小时前
GLM-5.3-NVFP4 部署实战系列[二]Docker 镜像选择与补丁镜像构建:纯 Python overlay,不重编一行 CUDA
python·docker·容器·vllm
CoderYanger2 小时前
A.每日一题:输入单词需要的最少按键次数 Ⅰ+Ⅱ
java·数据结构·算法·leetcode·面试
海兰2 小时前
【 Python 量化交易】第3章:金融基础概念
开发语言·python·金融
Feynman’s boom2 小时前
PDF解析文字提取后RAG仍然检索不准
python·pdf解析·rag