Skip to content

Latest commit

 

History

History
39 lines (28 loc) · 1.11 KB

329.md

File metadata and controls

39 lines (28 loc) · 1.11 KB

329 Longest Increasing Path in a Matrix

Description

link


Solution

  • Traditional DFS + Memoization

更新记录的DP map在dfs的过程当中,定义dfs得到的结果是当前坐标的解,本质上是动态规划,DFS是用于更新DP状态的工具


Code

O(?)

class Solution:
    def longestIncreasingPath(self, matrix: 'List[List[int]]') -> 'int':
        def dfs(i, j):
            if not dp[i][j]:
                val = matrix[i][j]
                dp[i][j] = 1 + max(
                    dfs(i - 1, j) if i and val > matrix[i - 1][j] else 0,
                    dfs(i + 1, j) if i < M - 1 and val > matrix[i + 1][j] else 0,
                    dfs(i, j - 1) if j and val > matrix[i][j - 1] else 0,
                    dfs(i, j + 1) if j < N - 1 and val > matrix[i][j + 1] else 0)
            return dp[i][j]

        if not matrix or not matrix[0]:
            return 0
        M, N = len(matrix), len(matrix[0])
        dp = [[0] * N for i in range(M)]
        return max(dfs(x, y) for x in range(M) for y in range(N))