Skip to content

Commit edae349

Browse files
Create Solution.py
1 parent 6661dfa commit edae349

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution:
2+
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
3+
4+
@lru_cache(None)
5+
def backtrack(i, j):
6+
result = 1
7+
val = matrix[i][j]
8+
matrix[i][j] = -1
9+
10+
for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:
11+
if not x >= 0 <= y: continue
12+
if not x < len(matrix): continue
13+
if not y < len(matrix[0]): continue
14+
if matrix[x][y] == -1: continue
15+
if matrix[x][y] <= val: continue
16+
result = max(result, backtrack(x, y)+1)
17+
18+
matrix[i][j] = val
19+
return result
20+
21+
22+
result = 0
23+
for i in range(len(matrix)):
24+
for j in range(len(matrix[0])):
25+
result = max(backtrack(i, j), result)
26+
27+
28+
return result

0 commit comments

Comments
 (0)