We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent a469aab commit fbae67cCopy full SHA for fbae67c
1 file changed
graphs/breadth_first_search.py
@@ -0,0 +1,40 @@
1
+# Breadth First Search
2
+
3
+from collections import defaultdict
4
5
+class Graph:
6
+ def __init__(self):
7
+ self.graph = defaultdict(list)
8
9
+ def add_edges(self,_from,_to):
10
+ for t in _to:
11
+ self.graph[_from].append(t)
12
13
+ def display(self):
14
+ print self.graph
15
16
+ def bfs(self,graph,start):
17
+ queue = [start]
18
+ visited = []
19
20
+ while queue:
21
+ a = queue.pop(0)
22
+ if a not in visited:
23
+ visited.append(a)
24
+ for neighbor in graph[a]:
25
+ queue.append(neighbor)
26
+ print visited
27
28
+def main():
29
30
+ G = Graph()
31
+ G.add_edges(1,[2,7,8])
32
+ G.add_edges(2,[3,6])
33
+ G.add_edges(3,[4,5])
34
+ G.add_edges(8,[9,12])
35
+ G.add_edges(9,[10,11])
36
+ G.display()
37
+ G.bfs(G.graph,1)
38
39
+if __name__ == '__main__':
40
+ main()
0 commit comments