-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall_paths_in_graph.py
More file actions
53 lines (42 loc) · 1.09 KB
/
Copy pathall_paths_in_graph.py
File metadata and controls
53 lines (42 loc) · 1.09 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
def all_paths(g, s, t):
n = len(g)
path = [None] * n
path[0] = s
data = {
'graph' : g,
'target' : t,
'n' : n
}
backtrack(path, 0, data)
def backtrack(path, step, data):
if path_found(path, step, data):
process_solution(path, step, data)
else:
step += 1
next_vertices = construct_next_vertices(path, step, data)
for i, vertex in enumerate(next_vertices):
path[step] = vertex
backtrack(path, step, data)
def path_found(path, step, data):
return data['target'] == path[step]
def process_solution(path, step, data):
print path[:step + 1]
def construct_next_vertices(path, step, data):
in_path = [False] * data['n']
next_vertices = []
for i in range(step):
in_path[ path[i] ] = True
last_vertex = path[step - 1]
for i, neighbor in enumerate(data['graph'][last_vertex]):
if not in_path[neighbor]:
next_vertices.append(neighbor)
return next_vertices
g = [
[1,3,2],
[0,4],
[0,3],
[0,2,4],
[1,3,5],
[5]
]
all_paths(g,2,5)