1. 程式人生 > >leetcode 矩陣中的最長遞增路徑 python【動態規劃】

leetcode 矩陣中的最長遞增路徑 python【動態規劃】

題目描述
在這裡插入圖片描述
**分析:**假設最長路徑終點的是[i][j],則其最長路徑值為nums1[i][j],則nums1[i][j]等於它上下左右四個數中,比它小的數中最長路徑值最大的那一個+1
因此,我們可以從矩陣的最小值出發,其最長路徑值為1,然後計算第二小的數的最長路徑值,以此類推

class Solution:
    def longestIncreasingPath(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: int
        """
        a = len(matrix)
        dic = {}
        nums_max = 1
        if a == 0:
            nums_max = 0
        else:
            b = len(matrix[0])
            for i in range(a):
                for j in range(b):
                    dic[(i,j)] = matrix[i][j]
            v =  dic.keys()
            nums1 = [[1 for i in range(b)] for j in range(a)]        
            dic = sorted(dic.items(),key = lambda x:x[1])
            for k in dic:
                i = k[0][0]
                j = k[0][1]
                if (i+1,j) in v and matrix[i+1][j]<matrix[i][j] and nums1[i][j]<nums1[i+1][j]+1:
                    nums1[i][j] = nums1[i+1][j] + 1
                if (i,j+1) in v and matrix[i][j+1]<matrix[i][j] and nums1[i][j]<nums1[i][j+1]+1:
                    nums1[i][j] = nums1[i][j+1] +1
                if (i-1,j) in v and matrix[i-1][j]<matrix[i][j] and nums1[i][j]<nums1[i-1][j]+1:
                    nums1[i][j] = nums1[i-1][j] +1
                if (i,j-1) in v and matrix[i][j-1]<matrix[i][j] and nums1[i][j]<nums1[i][j-1]+1:
                    nums1[i][j] = nums1[i][j-1] + 1    
                nums_max = max(nums_max,nums1[i][j])              
        return nums_max