File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
Graphs/Breadth First Search Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 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' )
You can’t perform that action at this time.
0 commit comments