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技术27 分钟前
【跨国数仓迁移最佳实践6】MaxCompute SQL语法及函数功能增强,10万条SQL转写顺利迁移
python·sql
杜子不疼.1 小时前
《Python学习之文件操作:从入门到精通》
数据库·python·学习
微小的xx1 小时前
java + html 图片点击文字验证码
java·python·html
金色旭光1 小时前
uv 现代化的虚拟环境管理工具
python·python进阶
赞哥哥s1 小时前
Python脚本开发-统计Rte中未连接的Port
python·autosar·rte
Franklin1 小时前
Python界面设计【QT-creator基础编程 - 01】如何让不同分辨率图像自动匹配graphicsView的窗口大小
开发语言·python·qt
waynaqua1 小时前
FastAPI开发AI应用三:添加深度思考功能
python·openai·deepseek
onejason2 小时前
《利用 Python 爬虫获取 Amazon 商品详情实战指南》
前端·后端·python
苏婳6662 小时前
【最新版】怎么下载mysqlclient并成功安装?
数据库·python·mysql
0wioiw03 小时前
Python基础(Flask①)
后端·python·flask