-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS and DFS.py
44 lines (41 loc) · 1002 Bytes
/
BFS and DFS.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def recursive_dfs(graph, start, path=[]):
'''recursive depth first search from start'''
path=path+[start]
for node in graph[start]:
if node not in path:
path=recursive_dfs(graph, node, path)
return path
def iterative_dfs(graph, start, path=[]):
'''iterative depth first search from start'''
q=[start]
while q:
v=q.pop(0)
if v not in path:
path=path+[v]
q=graph[v]+q
print ("graph", graph[v])
return path
def iterative_bfs(graph, start, path=[]):
'''iterative breadth first search from start'''
q=[start]
while q:
v=q.pop(0)
if not v in path:
path=path+[v]
q=q+graph[v]
return path
'''
+---- A
| / \
| B--D--C
| \ | /
+---- E
'''
graph = {'A':['B','C'],
'B':['D','E'],
'C':['D','E'],
'D':['E'],
'E':['A']}
print ('recursive dfs ', recursive_dfs(graph, 'A'))
print ('iterative dfs ', iterative_dfs(graph, 'A'))
print ('iterative bfs ', iterative_bfs(graph, 'A'))