3131#print adjacency matrix
3232print (adjacency_matrix )
3333
34- print ("--------------->" )
34+ print ("--------BFS----- ------->" )
3535
3636#Breadth First Search
3737graph = dict ()
@@ -63,3 +63,42 @@ def breadth_first_search(graph, root):
6363
6464
6565print (breadth_first_search (graph , 'A' ))
66+
67+
68+ print ("--------DFS------------>" )
69+ #Depth First Search
70+
71+ graph = dict ()
72+ graph ['A' ] = ['B' , 'S' ]
73+ graph ['B' ] = ['A' ]
74+ graph ['S' ] = ['A' ,'G' ,'C' ]
75+ graph ['D' ] = ['C' ]
76+ graph ['G' ] = ['S' ,'F' ,'H' ]
77+ graph ['H' ] = ['G' ,'E' ]
78+ graph ['E' ] = ['C' ,'H' ]
79+ graph ['F' ] = ['C' ,'G' ]
80+ graph ['C' ] = ['D' ,'S' ,'E' ,'F' ]
81+
82+ def depth_first_search (graph , root ):
83+ visited_vertices = list ()
84+ graph_stack = list ()
85+ graph_stack .append (root )
86+ node = root
87+
88+ while graph_stack :
89+ if node not in visited_vertices :
90+ visited_vertices .append (node )
91+ adjs_nodes = graph [node ]
92+ if set (adjs_nodes ).issubset (set (visited_vertices )):
93+ graph_stack .pop ()
94+ if len (graph_stack ) > 0 :
95+ node = graph_stack [- 1 ]
96+ continue
97+ else :
98+ remaining_elements = set (adjs_nodes ).difference (set (visited_vertices ))
99+ first_adj_node = sorted (remaining_elements )[0 ]
100+ graph_stack .append (first_adj_node )
101+ node = first_adj_node
102+ return visited_vertices
103+
104+ print (depth_first_search (graph , 'A' ))
0 commit comments