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

Function dfs

python3/Graphs/count_islands.py:17–27  ·  view source on GitHub ↗
(r: int, c: int, matrix: List[List[int]])

Source from the content-addressed store, hash-verified

15 return count
16
17def dfs(r: int, c: int, matrix: List[List[int]]) -> None:
18 # Mark the current land cell as visited.
19 matrix[r][c] = -1
20 # Define direction vectors for up, down, left, and right.
21 dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
22 # Recursively call DFS on each neighboring land cell to continue
23 # exploring this island.
24 for d in dirs:
25 next_r, next_c = r + d[0], c + d[1]
26 if is_within_bounds(next_r, next_c, matrix) and matrix[next_r][next_c] == 1:
27 dfs(next_r, next_c, matrix)
28
29def is_within_bounds(r: int, c: int, matrix: List[List[int]]) -> bool:
30 return 0 <= r < len(matrix) and 0 <= c < len(matrix[0])

Callers 1

count_islandsFunction · 0.70

Calls 1

is_within_boundsFunction · 0.70

Tested by

no test coverage detected