1+ from Queue import Queue
2+
3+ class Graph :
4+ def __init__ (self ):
5+ self .vertices = []
6+ self .adjacencyList = {}
7+ self .distance = {}
8+ self .previous = {}
9+
10+ def add_vertex (self , v ):
11+ self .vertices .append (v )
12+ self .adjacencyList [v ] = []
13+ self .distance [v ] = 0
14+ self .previous [v ] = None
15+
16+ def add_edge (self ,v1 , v2 ):
17+ self .adjacencyList [v1 ].append (v2 )
18+ self .adjacencyList [v2 ].append (v1 )
19+
20+ def to_string (self ):
21+ result = ""
22+ for vertex in self .vertices :
23+ result += (vertex + " -> " )
24+ for neighbour in self .adjacencyList [vertex ]:
25+ result += neighbour + " "
26+ result += "\n "
27+ return result
28+
29+ def breadth_first_search (self ):
30+ queue = Queue ()
31+ startVertex = self .vertices [0 ]
32+ gray = [] # visited, not fully explored
33+ black = [] # explored
34+ gray .append (startVertex )
35+ queue .enqueue (startVertex )
36+ while not queue .isEmpty ():
37+ dequeued = queue .dequeue ()
38+ if dequeued not in black :
39+ for neighbour in self .adjacencyList [dequeued ]:
40+ if neighbour not in gray :
41+ queue .enqueue (neighbour )
42+ gray .append (neighbour )
43+ self .distance [neighbour ] = self .distance [dequeued ] + 1
44+ self .previous [neighbour ] = dequeued
45+ black .append (dequeued )
46+ print ("Explored " + dequeued , end = " " )
47+ print ("" )
48+
49+ def showPath (self , vertex ):
50+ if self .previous [vertex ] == None :
51+ return vertex
52+ else :
53+ return self .showPath (self .previous [vertex ]) + " -> " + vertex
54+
55+ graph = Graph ()
56+
57+
58+ vertices = ['A' , 'B' , 'C' , 'D' , 'E' , 'F' ]
59+ # add vertices
60+ for i in range (len (vertices )):
61+ graph .add_vertex (vertices [i ])
62+
63+ graph .add_edge ('A' , 'B' )
64+ graph .add_edge ('A' , 'C' )
65+ graph .add_edge ('C' , 'D' )
66+ graph .add_edge ('D' , 'E' )
67+ graph .add_edge ('D' , 'F' )
68+
69+ print (graph .to_string ())
70+ print ("##########################" )
71+ graph .breadth_first_search ()
72+ print (graph .distance )
73+ print (graph .previous )
74+ print (graph .showPath ("F" ))
75+
76+
0 commit comments