-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs_dfs.py
46 lines (38 loc) · 1.34 KB
/
bfs_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
45
46
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
def bfs_paths(graph, start, goal):
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path):
if next == goal:
yield path + [next]
else:
queue.append((next, path + [next]))
def dfs_paths(graph, start, goal):
stack = [(start, [start])]
while stack:
(vertex, path) = stack.pop()
for next in graph[vertex] - set(path):
if next == goal:
yield path + [next]
else:
stack.append((next, path + [next]))
def shortest_path_bfs(graph, start, goal):
try:
return next(bfs_paths(graph, start, goal))
except StopIteration:
return None
def shortest_path_dfs(graph, start, goal):
try:
return next(dfs_paths(graph, start, goal))
except StopIteration:
return None
print("This is the shortest path for BFS from point A to F")
print(shortest_path_bfs(graph, 'A', 'F'))
print("This is the shortest path for DFS from point A to F")
print(shortest_path_dfs(graph, 'A', 'F'))