-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_path.py
More file actions
90 lines (60 loc) · 1.84 KB
/
find_path.py
File metadata and controls
90 lines (60 loc) · 1.84 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
""" a.k.a Depth first search
"""
# Recursive
def find_path(graph, start, end, path=[]):
if start not in graph: return None
path += [start]
# Path found. Base case
if start == end: return path
for node in graph[start]:
if node not in path:
# Recursively search path
return find_path(graph, node, end, path)
return None
# Non recursive
def depth_first(graph, start, end):
stack = [start]
path = [start]
while stack:
node = stack.pop()
if node == end: return path
for vertex in graph[node]:
if vertex not in path:
path.append(vertex)
stack.append(vertex)
return None
# All possible paths from start to end
def all_paths(graph, start, end, path=[]):
# Creates a new list so input path is not affected
path = path + [start]
if start not in graph: return None
if start == end: return [path]
paths = []
for node in graph[start]:
if node not in path:
new_paths = all_paths(graph, node, end, path)
for newpath in new_paths:
paths.append(newpath)
return paths
def shortest_path(graph, start, end, path=[]):
path = path + [start]
if start not in graph: return None
if start == end: return path
shortest = []
for node in graph[start]:
if node not in path:
new_path = shortest_path(graph, node, end, path)
if not shortest or len(new_path) < len(shortest):
shortest = new_path
return shortest
graph = {'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']
}
print(depth_first(graph, 'A', 'D'))
print(find_path(graph, 'A', 'D'))
print(all_paths(graph, 'A', 'D'))
print(shortest_path(graph, 'A', 'D'))