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
相关推荐
ゞ 正在缓冲99%…19 小时前
leetcode1771.由子序列构造的最长回文串长度
数据结构·算法·leetcode
B站_计算机毕业设计之家20 小时前
深度学习:Yolo水果检测识别系统 深度学习算法 pyqt界面 训练集测试集 深度学习 数据库 大数据 (建议收藏)✅
数据库·人工智能·python·深度学习·算法·yolo·pyqt
闲人编程20 小时前
用Python分析你的Spotify/网易云音乐听歌数据
开发语言·python·ai·数据分析·spotify·网易云·codecapsule
“负拾捌”21 小时前
LangChain 中 ChatPromptTemplate 的几种使用方式
python·langchain·prompt
咋吃都不胖lyh21 小时前
小白零基础教程:安装 Conda + VSCode 配置 Python 开发环境
人工智能·python·conda
闲人编程1 天前
构建一个短链接生成器服务(FastAPI + SQLite)
jvm·python·sqlite·fastapi·生成器·短链接·caodecapsule
杰瑞哥哥1 天前
标准 Python 项目结构
开发语言·python
西部森林牧歌1 天前
Arbess零基础学习 - 使用Arbess+GitLab实现Python项目构建/主机部署
python·ci/cd·gitlab·tiklab devops
Jay_Franklin1 天前
Python中使用sqlite3模块和panel完成SQLite数据库中PDF的写入和读取
数据库·笔记·python·pycharm·sqlite·pdf·py