-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest_Increasing_Path_329.py
More file actions
35 lines (26 loc) · 1.01 KB
/
Longest_Increasing_Path_329.py
File metadata and controls
35 lines (26 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import collections
from typing import List
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
memo = collections.defaultdict(int)
def isValid(r, c, prev):
if(min(r, c) < 0 or r >= len(matrix) or c >= len(matrix[0])):
return False
if(matrix[r][c] <= prev):
return False
return True
def dfs(r, c, prev):
if(not isValid(r, c, prev)):
return 0
if((r, c) in memo):
return memo[(r, c)]
down = 1 + dfs(r + 1, c, matrix[r][c])
up = 1 + dfs(r - 1, c, matrix[r][c])
right = 1 + dfs(r, c + 1, matrix[r][c])
left = 1 + dfs(r, c - 1, matrix[r][c])
memo[(r, c)] = max(down, up, right, left)
return memo[(r,c)]
for r in range(len(matrix)):
for c in range(len(matrix[0])):
dfs(r, c, -1)
return max(memo.values())