Problem description:

Given an m x n integers matrix, return the length of the longest increasing path in matrix.

From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).

Example 1:

https://assets.leetcode.com/uploads/2021/01/05/grid1.jpg

1
2
3
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The longest increasing path is[1, 2, 6, 9].

Example 2:

https://assets.leetcode.com/uploads/2021/01/27/tmp-grid.jpg

1
2
3
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Explanation:The longest increasing path is[3, 4, 5, 6]. Moving diagonally is not allowed.

Example 3:

1
2
Input: matrix = [[1]]
Output: 1

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 231 - 1

Solution:

  1. naive: check all the node and calculate
  2. Top down DP

for each cell, memorize the max increasing path could go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
# dp top down
# for each cell, memorize the max increasing path could go
self.res = 0
dp = defaultdict()
def dfs(x, y, prev):
if x < 0 or y < 0 or x >= len(matrix) or y >= len(matrix[0]) or matrix[x][y] <= prev:
return 0
if (x, y) in dp:
return dp[(x,y)]

path = 1+ max(dfs(x-1, y, matrix[x][y]), dfs(x+1, y, matrix[x][y]), dfs(x, y-1, matrix[x][y]), dfs(x, y+1, matrix[x][y]))

self.res = max(self.res, path)
dp[(x,y)] = path
return path

for i in range(len(matrix)):
for j in range(len(matrix[0])):
dfs(i, j, float("-inf"))
return self.res

time complexity: $O()$
space complexity: $O()$
reference:
related problem: