In python I have a graph as adjacency list presentation. and a distance from specific points to all other elements in the graph.
graph = {
1 :[2, 7],
2 :[1, 3],
3 :[2, 4, 8],
4 :[3, 5, 9],
5 :[4, 6, 9],
6 :[5, 8, 10],
7 :[1, 8,10],
8 :[3, 6, 7, 9],
9 :[4, 5, 8],
10:[7, 6]
}
distance = {1: 1, 2: 0, 3: 0, 4: 1, 5: 2, 6: 2, 7: 2, 8: 1, 9: 2, 10: 3}
How I can backtrack the path from an element: for instance if I will try to backtrack from 10, it should return:
[10, 7, 1, 2]
[10, 7, 8, 3]
[10, 6, 8, 3]
I tried to do this recursively
def findprev(graph, distance, el, path = []):
value = distance[el]
if value == 0:
print path
path = []
for i in graph[el]:
if value - 1 == distance[i]:
path.append(i)
path = findprev(graph, distance, i, path)
return path
but apparently I am losing something important, because the result is:
[7, 1, 2]
[8, 3]
[6, 8, 3]
Can anyone help to find a bug