329. 矩阵中的最长递增路径(Hard)

class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        if not matrix:
            return 0

        h,w = len(matrix),len(matrix[0])

        store = [[None]*(w) for i in range(h)]

        m = 0 #储存max路径值

        def search_nearby(i,j):
            nonlocal m

            compare = [] #储存可以比较的候选人

            #这个楼主很懒,还没想怎么简化下面的代码
            #反正下面四个代码块就是分别看一下上、下、左、右哪些格子的值可以当做候选人比较
            #上
            if i != 0 and matrix[i-1][j] < matrix[i][j]: #有上边且上边小于当前数的话
                compare.append(store[i-1][j]) if store[i-1][j] else compare.append(search_nearby(i-1,j))
            #左
            if j != 0 and matrix[i][j-1] < matrix[i][j]: #有左边且左边小于当前数的话
                compare.append(store[i][j-1]) if store[i][j-1] else compare.append(search_nearby(i,j-1))
            #下
            if i != h-1 and matrix[i+1][j] < matrix[i][j]: #有下边且下边小于当前数的话
                compare.append(store[i+1][j]) if store[i+1][j] else compare.append(search_nearby(i+1,j))
            #右
            if j != w-1 and matrix[i][j+1] < matrix[i][j]: #有右边且右边小于当前数的话
                compare.append(store[i][j+1]) if store[i][j+1] else compare.append(search_nearby(i,j+1))
            
            store[i][j] = max(compare)+1 if compare else 1
            #如果没有compare说明这是一个很小的数,是一个起始点,能组成的长度只有1
            #有的话就原来最长路径+1

            m = max(m,store[i][j])
            return (store[i][j])
        
        for i in range(h):
            for j in range(w):
                if not store[i][j]:
                    search_nearby(i,j)
        
        return m
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
# 递增路径的最大长度
# @param matrix int整型二维数组 描述矩阵的每个数
# @return int整型
class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        # write code here
        row = len(matrix)
        col = len(matrix[0])
        temp = [[0] * col for _ in range(row)]
        
        def dfs(i, j): # 以matrix[i][j]为起点的最长递增路径长度
            res = 1
            for x,y in[(i-1,j),(i+1,j),(i,j-1),(i,j+1)]:
                # 若不越界 且 当前值大于前一个值(递增)
                if 0<=x<row and 0<=y<col and matrix[x][y] > matrix[i][j]:
                    # 若未遍历过,则进行深度遍历获得最长路径值
                    if temp[x][y] == 0:
                        res = max(res,dfs(x,y)+1)
                    # 若已经遍历过,则直接取出值来获得最长路径值
                    else:
                        res = max(res,temp[x][y]+1)
            temp[i][j] = res # 记录当前位置的最长路径值
            return res
        
        ans = 1
        for i in range(row):
            for j in range(col):
                ans = max(ans,dfs(i,j))
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值