I am trying to create a backtrace function the will return a list of the order of the shortest path from the root to the GOAL
My path_holder:
path_holder = {
'node1':['node2','node3','node5'],
'node2':['node1','node8','node10'],
'node3':['node4','node6']},
'node4':['node2','node1','node3'],
'node5':['DEADEND'],
'node6':['GOAL']
....
}
In my path_holder input, it is the output of a BFS so the first node is the root and the last node is the goal. Because the path_holder input is the output of a BFS, it stops when the GOAL is found so all the nodes that are branches of the previous nodes required to search for GOAL are added to path_holder as well.
Currently I am getting stuck in the while loop where an infinite loop occurs. My general strategy to is to start from the GOAL node and use the key of this node to find where this key is located in another key's(node) list. Once I found that node (where it's list contains the key), I set the node's key to be the new goal. (Confusing sentence sorry)
This graph may contain cycles which might be why I am also getting infinite loops.
my backtrace function:
def backtrace(path_holder, root, goal):
dct = {}
for d in path_holder:
dct.update(d)
rootnode = root.keys()[0]
goal = goal.keys()[0]
#x = len(path_holder)
path = []
path.append(goal)
#for i in reversed(xrange(x):
# path_holder[i].keys()
while goal != rootnode:
# find key that contains goal in list
for i in dct:
#print i
for j in dct[i] :
if j not in path:
if j == goal:
path.append(i)
goal = i
# append key that has goal in the list
# set goal to be the key that was appended
# repeat
return path
ex: output
path = ['node1','node3','node6']
while goal != rootnode:?if j not in pathhelps ignore cycles and allows full searches without getting stuck in a loop. correct me if im wrongpath_holderit is a list of dictionaries that contain a list. ex:a = [ {'node1':['node2','node3','node5']}, {'node2':['node1','node8','node10']}, {'node3':['node4','node2']}, {'node4':['node2','node1','node3']}, {'node5':['DEADEND']}, {'node6':['GOAL']} .... ]However I converted them to one big dictionary. Forrootandgoalthey are both dicionaries. EX of goal would be{'nodex':['GOAL']}and root would be{'node 1':['node2','node3','node4]'}