File tree Expand file tree Collapse file tree
BreadthFirstSearch/Python Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+
2+ from collections import defaultdict
3+
4+ # This class represents a directed graph using adjacency list representation
5+ class Graph :
6+ # Constructor
7+ def __init__ (self ):
8+
9+ # default dictionary to store graph
10+ self .graph = defaultdict (list )
11+
12+ # function to add an edge to graph
13+ def addEdge (self ,u ,v ):
14+ self .graph [u ].append (v )
15+
16+ # Function to print a BFS of graph
17+ def BFS (self , s ):
18+
19+ # Mark all the vertices as not visited
20+ visited = [False ]* (len (self .graph ))
21+
22+ # Create a queue for BFS
23+ queue = []
24+
25+ # Mark the source node as visited and enqueue it
26+ queue .append (s )
27+ visited [s ] = True
28+
29+ while queue :
30+
31+ # Dequeue a vertex from queue and print it
32+ s = queue .pop (0 )
33+ print s ,
34+
35+ # Get all adjacent vertices of the dequeued
36+ # vertex s. If a adjacent has not been visited,
37+ # then mark it visited and enqueue it
38+ for i in self .graph [s ]:
39+ if visited [i ] == False :
40+ queue .append (i )
41+ visited [i ] = True
42+
43+
44+ # Driver code
45+ # Create a graph given in the above diagram
46+ g = Graph ()
47+ g .addEdge (0 , 1 )
48+ g .addEdge (0 , 2 )
49+ g .addEdge (1 , 2 )
50+ g .addEdge (2 , 0 )
51+ g .addEdge (2 , 3 )
52+ g .addEdge (3 , 3 )
53+
54+ print g .BFS (1 )
You can’t perform that action at this time.
0 commit comments