forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbreadth_first_search_2.py
88 lines (73 loc) · 2.27 KB
/
breadth_first_search_2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""
https://en.wikipedia.org/wiki/Breadth-first_search
pseudo-code:
breadth_first_search(graph G, start vertex s):
// all nodes initially unexplored
mark s as explored
let Q = queue data structure, initialized with s
while Q is non-empty:
remove the first node of Q, call it v
for each edge(v, w): // for w in graph[v]
if w unexplored:
mark w as explored
add w to Q (at the end)
"""
from __future__ importannotations
fromcollectionsimportdeque
fromqueueimportQueue
fromtimeitimporttimeit
G= {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
defbreadth_first_search(graph: dict, start: str) ->list[str]:
"""
Implementation of breadth first search using queue.Queue.
>>> ''.join(breadth_first_search(G, 'A'))
'ABCDEF'
"""
explored= {start}
result= [start]
queue: Queue=Queue()
queue.put(start)
whilenotqueue.empty():
v=queue.get()
forwingraph[v]:
ifwnotinexplored:
explored.add(w)
result.append(w)
queue.put(w)
returnresult
defbreadth_first_search_with_deque(graph: dict, start: str) ->list[str]:
"""
Implementation of breadth first search using collection.queue.
>>> ''.join(breadth_first_search_with_deque(G, 'A'))
'ABCDEF'
"""
visited= {start}
result= [start]
queue=deque([start])
whilequeue:
v=queue.popleft()
forchildingraph[v]:
ifchildnotinvisited:
visited.add(child)
result.append(child)
queue.append(child)
returnresult
defbenchmark_function(name: str) ->None:
setup=f"from __main__ import G, {name}"
number=10000
res=timeit(f"{name}(G, 'A')", setup=setup, number=number)
print(f"{name:<35} finished {number} runs in {res:.5f} seconds")
if__name__=="__main__":
importdoctest
doctest.testmod()
benchmark_function("breadth_first_search")
benchmark_function("breadth_first_search_with_deque")
# breadth_first_search finished 10000 runs in 0.20999 seconds
# breadth_first_search_with_deque finished 10000 runs in 0.01421 seconds