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
相关推荐
geyasi4 分钟前
【Flask】四、flask连接并操作数据库
数据库·python·flask
DeepModel6 分钟前
机器学习降维:多维尺度分析 MDS
人工智能·python·机器学习
GinoWi19 分钟前
Chapter 8 Python中的类
python
Thomas.Sir23 分钟前
第六章:RAG知识库开发之【深入浅出RAG使用效果评估:从指标到实践】
人工智能·python·ai·rag·效果评估
菜菜的顾清寒25 分钟前
力扣HOT100(16)除了自身以外数组的乘积
算法·leetcode·职场和发展
老虎062737 分钟前
LeetCode热题100 刷题笔记(第六天)双指针 「 盛最多水的容器」
笔记·算法·leetcode
飞Link37 分钟前
深入挖掘 LangChain Community 核心组件,从数据接入到企业级 RAG 实战
开发语言·python·langchain
SuperEugene39 分钟前
Python + venv + VSCode:前端工程师 AI 转型入门 | 基础篇
前端·人工智能·vscode·python
IT空门:门主1 小时前
Anaconda & uv 常用命令速查手册
python·uv
2601_949816161 小时前
使用python进行PostgreSQL 数据库连接
数据库·python·postgresql