1+ from Stack import Stack
2+ from collections import OrderedDict
3+
4+ class Graph :
5+ def __init__ (self ):
6+ self .vertices = []
7+ self .adjacencyList = {}
8+ self .distance = {}
9+ self .previous = {}
10+ self .visited = []
11+
12+ def add_vertex (self , v ):
13+ self .vertices .append (v )
14+ self .adjacencyList [v ] = []
15+ self .distance [v ] = 0
16+ self .previous [v ] = None
17+
18+ def add_edge (self ,v1 , v2 ):
19+ self .adjacencyList [v1 ].append (v2 )
20+ #self.adjacencyList[v2].append(v1) DIRECTED ACYCLIC GRAPHS ONLY
21+
22+ def to_string (self ):
23+ result = ""
24+ for vertex in self .vertices :
25+ result += (vertex + " -> " )
26+ for neighbour in self .adjacencyList [vertex ]:
27+ result += neighbour + " "
28+ result += "\n "
29+ return result
30+
31+ def breadth_first_search (self ):
32+ for vertex in self .vertices :
33+ self .search_helper (vertex )
34+
35+ sorted_x = sorted (self .distance .items (), key = lambda kv : kv [1 ])
36+ sorted_dict = OrderedDict (sorted_x )
37+ print (sorted_dict )
38+
39+ def search_helper (self , vertex ):
40+ self .visited .append (vertex )
41+ stack = Stack ()
42+ stack .push (vertex )
43+ self .visited .append (vertex )
44+ while not stack .isEmpty ():
45+ peeked_vertex = stack .peek ()
46+ new_vertex = self .find_unvisited_neighbour (peeked_vertex )
47+ if new_vertex != None :
48+ self .previous [new_vertex ] = peeked_vertex
49+ self .distance [new_vertex ] = self .distance [peeked_vertex ] + 1
50+ self .visited .append (new_vertex )
51+ stack .push (new_vertex )
52+ else :
53+ stack .pop ()
54+
55+ def find_unvisited_neighbour (self , vertex ):
56+ found = False
57+ count = 0
58+ while count < len (self .adjacencyList [vertex ]) and not found :
59+ if self .adjacencyList [vertex ][count ] not in self .visited :
60+ found = True
61+ else :
62+ count += 1
63+ if found :
64+ return self .adjacencyList [vertex ][count ]
65+ else :
66+ return None
67+
68+ graph = Graph ()
69+
70+
71+ vertices = ['A' , 'B' , 'C' , 'D' , 'E' ]
72+ # add vertices
73+ for i in range (len (vertices )):
74+ graph .add_vertex (vertices [i ])
75+
76+ graph .add_edge ('A' , 'B' )
77+ graph .add_edge ('C' , 'B' )
78+ graph .add_edge ('B' , 'D' )
79+ graph .add_edge ('D' , 'E' )
80+
81+ print (graph .to_string ())
82+ print ("##########################" )
83+ graph .breadth_first_search ()
84+ print (graph .distance )
85+ print (graph .previous )
86+ print (graph .distance )
87+
88+
89+
0 commit comments