Skip to content

Commit a654750

Browse files
authoredDec 20, 2021
Create 329-Longest-Increasing-Path-in-a-Matrix.py
1 parent 9d079c2 commit a654750

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
 
+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
3+
ROWS, COLS = len(matrix), len(matrix[0])
4+
dp = {} # (r, c) -> LIP
5+
6+
def dfs(r, c, prevVal):
7+
if (r < 0 or r == ROWS or
8+
c < 0 or c == COLS or
9+
matrix[r][c] <= prevVal):
10+
return 0
11+
if (r, c) in dp:
12+
return dp[(r, c)]
13+
14+
res = 1
15+
res = max(res, 1 + dfs(r + 1, c, matrix[r][c]))
16+
res = max(res, 1 + dfs(r - 1, c, matrix[r][c]))
17+
res = max(res, 1 + dfs(r, c + 1, matrix[r][c]))
18+
res = max(res, 1 + dfs(r, c - 1, matrix[r][c]))
19+
dp[(r, c)] = res
20+
return res
21+
22+
for r in range(ROWS):
23+
for c in range(COLS):
24+
dfs(r, c, -1)
25+
return max(dp.values())

0 commit comments

Comments
 (0)
Please sign in to comment.