File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 2929 adjacency_matrix [node1 ][node2 ] = 1
3030
3131#print adjacency matrix
32- print (adjacency_matrix )
32+ print (adjacency_matrix )
33+
34+ print ("--------------->" )
35+
36+ #Breadth First Search
37+ graph = dict ()
38+ graph ['A' ] = ['B' , 'G' , 'D' ]
39+ graph ['B' ] = ['A' , 'F' , 'E' ]
40+ graph ['C' ] = ['F' , 'H' ]
41+ graph ['D' ] = ['F' , 'A' ]
42+ graph ['E' ] = ['B' , 'G' ]
43+ graph ['F' ] = ['B' , 'D' , 'C' ]
44+ graph ['G' ] = ['A' , 'E' ]
45+ graph ['H' ] = ['C' ]
46+
47+ from collections import deque
48+
49+ def breadth_first_search (graph , root ):
50+ visited_vertices = list ()
51+ graph_deque = deque ([root ])
52+ visited_vertices .append (root )
53+ node = root
54+ while len (graph_deque ) > 0 :
55+ node = graph_deque .popleft ()
56+ adj_nodes = graph [node ]
57+ remaining_elements = set (adj_nodes ).difference (set (visited_vertices ))
58+ if len (remaining_elements ) > 0 :
59+ for elem in sorted (remaining_elements ):
60+ visited_vertices .append (elem )
61+ graph_deque .append (elem )
62+ return visited_vertices
63+
64+
65+ print (breadth_first_search (graph , 'A' ))
You can’t perform that action at this time.
0 commit comments