File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Breadth First Search
2
+
3
+ from collect
8000
ions 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 ()
You can’t perform that action at this time.
0 commit comments