码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-329-矩阵中的最长递增路径

时间:2020-07-27 15:46:06      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:obj   incr   not   技术   inf   etc   src   nbsp   动态规划   

题目描述:

技术图片

 

 技术图片

 

 方法一:动态规划 O(mnlogmn)

class Solution(object):
    def longestIncreasingPath(self, matrix):
        if not matrix or not matrix[0]:
            return 0
        m, n = len(matrix), len(matrix[0])
        lst = []
        for i in range(m):
            for j in range(n):
                lst.append((matrix[i][j], i, j))
        lst.sort()
        dp = [[0 for _ in range(n)] for _ in range(m)]
        for num, i, j in lst:
            dp[i][j] = 1
            for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
                r, c = i + di, j + dj
                if 0 <= r < m and 0 <= c < n:
                    if matrix[i][j] > matrix[r][c]:
                        dp[i][j] = max(dp[i][j], 1 + dp[r][c])
        return max([dp[i][j] for i in range(m) for j in range(n)])

方法二:记忆化深搜 O(mn) O(mn)

class Solution(object):
    def longestIncreasingPath(self, matrix):
        if not matrix or not matrix[0]:
            return 0
        dirs = [(0,-1),(0,1),(1,0),(-1,0)]

        rows,columns = len(matrix),len(matrix[0])

        @lru_cache(None)
        def helper(row,column):
            best = 1
            for _i,_j in dirs:
                newrow,newcolumn = row + _i,column + _j
                if 0 <= newrow < rows and 0 <= newcolumn < columns and matrix[row][column] < matrix[newrow][newcolumn]:
                    best = max(best,helper(newrow,newcolumn) + 1)
            return best
        
        ans = 0
        for i in range(rows):
            for j in range(columns):
                ans = max(ans,helper(i,j))
        return ans

 

leetcode-329-矩阵中的最长递增路径

标签:obj   incr   not   技术   inf   etc   src   nbsp   动态规划   

原文地址:https://www.cnblogs.com/oldby/p/13384749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!