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

Function depth_first_search

graphs/depth_first_search.py:6–31  ·  view source on GitHub ↗

Depth First Search on Graph :param graph: directed graph in dictionary format :param start: starting vertex as a string :returns: the trace of the search >>> input_G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], ... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], ... "F"

(graph: dict, start: str)

Source from the content-addressed store, hash-verified

4
5
6def depth_first_search(graph: dict, start: str) -> set[str]:
7 """Depth First Search on Graph
8 :param graph: directed graph in dictionary format
9 :param start: starting vertex as a string
10 :returns: the trace of the search
11 >>> input_G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"],
12 ... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"],
13 ... "F": ["C", "E", "G"], "G": ["F"] }
14 >>> output_G = list({'A', 'B', 'C', 'D', 'E', 'F', 'G'})
15 >>> all(x in output_G for x in list(depth_first_search(input_G, "A")))
16 True
17 >>> all(x in output_G for x in list(depth_first_search(input_G, "G")))
18 True
19 """
20 explored, stack = set(start), [start]
21
22 while stack:
23 v = stack.pop()
24 explored.add(v)
25 # Differences from BFS:
26 # 1) pop last element instead of first one
27 # 2) add adjacent elements to stack without exploring them
28 for adj in reversed(graph[v]):
29 if adj not in explored:
30 stack.append(adj)
31 return explored
32
33
34G = {

Callers 1

Calls 3

popMethod · 0.45
addMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected