MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / dfs

Function dfs

python3/Graphs/longest_increasing_path.py:18–30  ·  view source on GitHub ↗
(r: int, c: int, matrix: List[List[int]], memo: List[List[int]])

Source from the content-addressed store, hash-verified

16 return res
17
18def dfs(r: int, c: int, matrix: List[List[int]], memo: List[List[int]]) -> int:
19 if memo[r][c] != 0:
20 return memo[r][c]
21 max_path = 1
22 dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
23 # The longest path starting at the current cell is equal to the
24 # longest path of its larger neighboring cells, plus 1.
25 for d in dirs:
26 next_r, next_c = r + d[0], c + d[1]
27 if is_within_bounds(next_r, next_c, matrix) and matrix[next_r][next_c] > matrix[r][c]:
28 max_path = max(max_path, 1 + dfs(next_r, next_c, matrix, memo))
29 memo[r][c] = max_path
30 return max_path
31
32def is_within_bounds(r: int, c: int, matrix: List[List[int]]) -> bool:
33 return 0 <= r < len(matrix) and 0 <= c < len(matrix[0])

Callers 1

longest_increasing_pathFunction · 0.70

Calls 1

is_within_boundsFunction · 0.70

Tested by

no test coverage detected