Skip to content

Commit 0e7e4d8

Browse files
authored
Create bfs.py
1 parent 9296a10 commit 0e7e4d8

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Graphs/Breadth First Search/bfs.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Create a graph given in the above diagram.
2+
graph = {
3+
'A': ['B', 'C', 'D'],
4+
'B': ['A'],
5+
'C': ['A', 'D'],
6+
'D': ['A', 'C', 'E'],
7+
'E': ['D']
8+
}
9+
10+
# to print a BFS of a graph
11+
def bfs(node):
12+
13+
# mark vertices as False means not visited
14+
visited = [False] * (len(graph))
15+
16+
# make a empty queue for bfs
17+
queue = []
18+
19+
# mark given node as visited and add it to the queue
20+
visited.append(node)
21+
queue.append(node)
22+
23+
while queue:
24+
# Remove the front vertex or the vertex at 0th index from the queue and print that vertex.
25+
v = queue.pop(0)
26+
print(v, end=" ")
27+
28+
for neigh in graph[v]:
29+
if neigh not in visited:
30+
visited.append(neigh)
31+
queue.append(neigh)
32+
33+
34+
# Driver Code
35+
if __name__ == "__main__":
36+
bfs('A')

0 commit comments

Comments
 (0)