Skip to content

Commit f97efb0

Browse files
committed
update
1 parent 5f899bb commit f97efb0

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

[K]graph/[K]graph-dfs/329-longest-increasing-path-in-a-matrix.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
11
class Solution:
22
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
3-
res = 0
43
rows, cols = len(matrix), len(matrix[0])
5-
counts = [[- 1 for _ in range(cols)] for _ in range(rows)]
4+
cell_len = {}
65

76
def dfs(r, c):
8-
next_count = 0
7+
total = 1
8+
new_total = total
99
for next_r, next_c in [(r+1, c), (r-1, c), (r, c+1), (r, c-1)]:
1010
if next_r not in range(rows) or next_c not in range(cols) or matrix[r][c] >= matrix[next_r][next_c]:
1111
continue
12-
if counts[next_r][next_c] == - 1:
13-
next_count = max(next_count, dfs(next_r, next_c))
12+
if (next_r, next_c) in cell_len:
13+
new_total = max(new_total, total + cell_len[(next_r, next_c)])
1414
else:
15-
next_count = max(next_count, counts[next_r][next_c])
16-
counts[r][c] = 1 + next_count
17-
return counts[r][c]
18-
15+
new_total = max(new_total, total + dfs(next_r, next_c))
16+
cell_len[(r, c)] = new_total
17+
return new_total
18+
1919
for r in range(rows):
2020
for c in range(cols):
21-
res = max(res, dfs(r, c))
22-
return res
21+
dfs(r, c)
22+
return max(cell_len.values())
2323

2424
# time O(RC)
2525
# space O(RC)

0 commit comments

Comments
 (0)