MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / dfs

Function dfs

graphs/connected_components.py:13–30  ·  view source on GitHub ↗

Use depth first search to find all vertices being in the same component as initial vertex >>> dfs(test_graph_1, 0, 5 * [False]) [0, 1, 3, 2] >>> dfs(test_graph_2, 0, 6 * [False]) [0, 1, 3, 2]

(graph: dict, vert: int, visited: list)

Source from the content-addressed store, hash-verified

11
12
13def dfs(graph: dict, vert: int, visited: list) -> list:
14 """
15 Use depth first search to find all vertices
16 being in the same component as initial vertex
17 >>> dfs(test_graph_1, 0, 5 * [False])
18 [0, 1, 3, 2]
19 >>> dfs(test_graph_2, 0, 6 * [False])
20 [0, 1, 3, 2]
21 """
22
23 visited[vert] = True
24 connected_verts = []
25
26 for neighbour in graph[vert]:
27 if not visited[neighbour]:
28 connected_verts += dfs(graph, neighbour, visited)
29
30 return [vert, *connected_verts]
31
32
33def connected_components(graph: dict) -> list:

Callers 1

connected_componentsFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected