Skip to content

Commit 89a1dcb

Browse files
committed
Graphs.py changed
1 parent e4cc0cb commit 89a1dcb

1 file changed

Lines changed: 34 additions & 1 deletion

File tree

DataStructures/Section8/Graphs.py

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,37 @@
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'))

0 commit comments

Comments
 (0)