Reputation: 9480
I have been going through the algorithm of uniform-cost search and even though I am able to understand the whole priority queue procedure I am not able to understand the final stage of the algorithm.
If we look at this graph, after applying the algorithm I will have the minimum distance for each node, but suppose I want to know the path between A to G (just like the example), how will I compute that?
Upvotes: 8
Views: 38753
Reputation: 105886
Usually you start with a infinite total cost for every node that hasn't been explored yet. Then you can adjust the algorithm a little bit to save the predecessor:
for each of node's neighbours n
if n is not in explored
if n is not in frontier
frontier.add(n)
set n's predecessor to node
elif n is in frontier with higher cost
replace existing node with n
set n's predecessor to node
Afterwards you can just check the sequence of predecessors, starting at your goal.
Upvotes: 14
Reputation: 889
Visit for more info https://www.youtube.com/watch?v=9vNvrRP0ymw
Insert the root into the queue
While the queue is not empty
Dequeue the maximum priority element from the queue
(If priorities are same, alphabetically smaller path is chosen)
If the path is ending in the goal state, print the path and exit
Else
Insert all the children of the dequeued element, with the cumulative costs as priority
Upvotes: 0