Skip to content

Commit c66528c

Browse files
author
ybenchekroun
authored
Create BreadtFirstSearch_2.py
1 parent 0aec412 commit c66528c

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Graphs/BreadtFirstSearch_2.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# From https://www.educative.io/edpresso/how-to-implement-a-breadth-first-search-in-python
2+
3+
def bfs(graph, node):
4+
visited = [] # List to keep track of visited nodes.
5+
queue = [] #Initialize a queue
6+
7+
visited.append(node)
8+
queue.append(node)
9+
10+
while queue:
11+
s = queue.pop(0)
12+
print(s, end = " ")
13+
14+
for neighbour in graph[s]:
15+
if neighbour not in visited:
16+
visited.append(neighbour)
17+
queue.append(neighbour)
18+
19+
20+
# Driver Code
21+
22+
graph = {
23+
'A' : ['B','C'],
24+
'B' : ['D', 'E'],
25+
'C' : ['F'],
26+
'D' : [],
27+
'E' : ['F'],
28+
'F' : []
29+
}
30+
31+
bfs(graph, 'C')

0 commit comments

Comments
 (0)