-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathbreadth_first_search.py
More file actions
53 lines (43 loc) · 1.29 KB
/
Copy pathbreadth_first_search.py
File metadata and controls
53 lines (43 loc) · 1.29 KB
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
""" Breadth-First Search Graph Traversal Algorithm
Breadth-First Search is a traversing algorithm where you should start
traversing from a selected node (source or starting node) and traverse
the graph layerwise thus exploring the neighbour nodes (nodes which
are directly connected to source node). You must then move towards the
next-level neighbour nodes.
Time Complexity: O(V+E)
Space Complexity: O(V)
"""
from collections import deque
def breadth_first_search(graph, root):
""" graph traversal algorithm
breadth first search implementation
"""
visited = set()
queue = deque([root])
visited.add(root)
while queue:
vertex = queue.popleft()
print(str(vertex), end=" ")
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
def main():
""" operational function """
graph = {
"A": ["B", "C", "D"],
"B": ["E"],
"C": ["F", "G"],
"D": ["H"],
"E": ["I"],
"F": ["J"],
"G": [],
"H": [],
"I": [],
"J": []
}
print("Breadth First Traversal: ", end="")
breadth_first_search(graph, "A")
print()
if __name__ == "__main__":
main()