5
5
6
6
class Graph :
7
7
def __init__ (self ):
8
- self .vertex = {}
8
+ self .vertices = {}
9
9
10
- # for printing the Graph vertices
11
10
def printGraph (self ):
12
- for i in self .vertex .keys ():
13
- print (i , " -> " , " -> " .join ([str (j ) for j in self .vertex [i ]]))
11
+ """prints adjacency list representation of graaph"""
12
+ for i in self .vertices .keys ():
13
+ print (i , " : " , " -> " .join ([str (j ) for j in self .vertices [i ]]))
14
14
15
- # for adding the edge between two vertices
16
15
def addEdge (self , fromVertex , toVertex ):
17
- # check if vertex is already present,
18
- if fromVertex in self .vertex .keys ():
19
- self .vertex [fromVertex ].append (toVertex )
16
+ """adding the edge between two vertices"""
17
+ if fromVertex in self .vertices .keys ():
18
+ self .vertices [fromVertex ].append (toVertex )
20
19
else :
21
- # else make a new vertex
22
- self .vertex [fromVertex ] = [toVertex ]
20
+ self .vertices [fromVertex ] = [toVertex ]
23
21
24
22
def BFS (self , startVertex ):
25
- # Take a list for stoting already visited vertices
26
- visited = [ False ] * len ( self . vertex )
23
+ # initialize set for storing already visited vertices
24
+ visited = set ( )
27
25
28
- # create a list to store all the vertices for BFS
26
+ # create a first in first out queue to store all the vertices for BFS
29
27
queue = []
30
28
31
29
# mark the source node as visited and enqueue it
32
- visited [ startVertex ] = True
30
+ visited . add ( startVertex )
33
31
queue .append (startVertex )
34
32
35
33
while queue :
36
- startVertex = queue .pop (0 )
37
- print (startVertex , end = " " )
34
+ vertex = queue .pop (0 )
38
35
39
- # mark all adjacent nodes as visited and print them
40
- for i in self .vertex [startVertex ]:
41
- if visited [i ] == False :
42
- queue .append (i )
43
- visited [i ] = True
36
+ # loop through all adjacent vertex and enqueue it if not yet visited
37
+ for adjacent_vertex in self .vertices [vertex ]:
38
+ if adjacent_vertex not in visited :
39
+ queue .append (adjacent_vertex )
40
+ visited .add (adjacent_vertex )
41
+ return visited
44
42
45
43
46
44
if __name__ == "__main__" :
@@ -53,13 +51,9 @@ def BFS(self, startVertex):
53
51
g .addEdge (3 , 3 )
54
52
55
53
g .printGraph ()
56
- print ("BFS:" )
57
- g .BFS (2 )
54
+ # 0 : 1 -> 2
55
+ # 1 : 2
56
+ # 2 : 0 -> 3
57
+ # 3 : 3
58
58
59
- # OUTPUT:
60
- # 0 -> 1 -> 2
61
- # 1 -> 2
62
- # 2 -> 0 -> 3
63
- # 3 -> 3
64
- # BFS:
65
- # 2 0 3 1
59
+ assert sorted (g .BFS (2 )) == [0 , 1 , 2 , 3 ]
0 commit comments