Skip to content

Commit b14be03

Browse files
committed
Create bfs_dfs.py
1 parent 1db398d commit b14be03

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

reinforcement_learning/bfs_dfs.py

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

0 commit comments

Comments
 (0)