-
Notifications
You must be signed in to change notification settings - Fork 1
/
graph_search.py
35 lines (26 loc) · 1006 Bytes
/
graph_search.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
def bfs(graph, start_vertex, target_value):
path = [start_vertex]
vertex_and_path = [start_vertex, path]
bfs_queue = [vertex_and_path]
visited = set()
while bfs_queue:
current_vertex, path = bfs_queue.pop(0)
visited.add(current_vertex)
for neighbor in graph[current_vertex]:
#print("The neighbours are: {0}".format(neighbor))
if neighbor not in visited:
if neighbor == target_value:
return path + [neighbor]
else:
bfs_queue.append([neighbor, path + [neighbor]])
def dfs(graph, current_vertex, target_value, visited = None):
if visited is None:
visited = []
visited.append(current_vertex)
if current_vertex == target_value:
return visited
for neighbor in graph[current_vertex]:
if neighbor not in visited:
path = dfs(graph, neighbor, target_value, visited)
if path:
return path