1+ # vertices or nodes in a given graph
2+ class Node (object ):
3+ def __init__ (self , name ):
4+ self .name = name # Name of Node
5+ self .adjacencyList = [] # Adjacency List
6+ self .visited = False # Boolean check if visited node or not
7+ self .predecessor = None # previous Vertex/Node in BFS
8+ # Bredth First Search
9+ class BredthFirstSearch (object ):
10+ # startNode: Starting Node from where we need to start BFS
11+ def bfs (self ,startNode ):
12+ #For BFS, using Queue as ADT
13+ queue = []
14+ #Initially , first value in the queue
15+ queue .append (startNode )
16+ #That node is visited, so true
17+ startNode .visited = True
18+
19+
20+ # while queue is not empty
21+ while queue :
22+ # actual node is the first node. FIFO Queue
23+ actualNode = queue .pop (0 )
24+ print ('%s' % actualNode .name )
25+
26+
27+ #visit all Neighbors of the current Node
28+ for n in actualNode .adjacencyList :
29+ #If Neighboring Node has not been visited, set visited to True and add to queue
30+ if not n .visited :
31+ n .visited = True
32+ queue .append (n )
33+
34+
35+ #Testing
36+ if __name__ == '__main__' :
37+ node1 = Node ('Á' )
38+ node2 = Node ('B' )
39+ node3 = Node ('C' )
40+ node4 = Node ('D' )
41+ node5 = Node ('E' )
42+ node6 = Node ('F' )
43+
44+ node1 .adjacencyList .append (node2 )
45+ node1 .adjacencyList .append (node3 )
46+ node2 .adjacencyList .append (node4 )
47+ node4 .adjacencyList .append (node5 )
48+ node4 .adjacencyList .append (node6 )
49+
50+ BFS = BredthFirstSearch ()
51+ BFS .bfs (node1 )
52+
53+ # -------------------------- EOC --------------------------
0 commit comments