File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ import networkx as nx
2+
3+ def breadth_first_search (graph , start ):
4+ visited = []
5+ queue = [start ]
6+ while queue :
7+ node = queue .pop (0 )
8+ if node not in visited :
9+ visited .append (node )
10+ neighbors = graph .neighbors (node )
11+ for n in neighbors :
12+ queue .append (n )
13+ return visited
14+
15+ def depth_first_search (graph , node , path = []):
16+ path += [node ]
17+ for n in graph .neighbors (node ):
18+ if n not in path :
19+ path = depth_first_search (graph , n , path )
20+ return path
21+
22+ if __name__ == '__main__' :
23+ graph_dict = {'A' :['B' , 'C' , 'D' ],
24+ 'B' :['E' ],
25+ 'C' :['F' ],
26+ 'D' :['G' , 'H' ],
27+ 'E' :[],
28+ 'F' :['I' , 'J' ],
29+ 'G' :[],
30+ 'H' :[],
31+ 'I' :[],
32+ 'J' :[]
33+ }
34+ G = nx .DiGraph (graph_dict )
35+ nx .draw (G , with_labels = True )
36+ print (breadth_first_search (G , 'A' ))
37+ print (depth_first_search (G , 'A' ))
You can’t perform that action at this time.
0 commit comments