Skip to content
Advertisement

For Dijkstra’s algorithm, what would be a way to keep track of and store the vertices that each shortest path contains?

I have it coded it out to update all the costs of the edges and such to complete Dijkstra’s main goal of finding the shortest path from the source vertex to all other vertices.

But I what I need help on is figuring out a way to store the vertices that each shortest path contains into an array that contains each path’s vertices that it passed through.

So for example let’s say the shortest path from the source vertex (A) to vertex (Z) is A -> B -> V – > Z. The shortest path goes through vertices B and V in order to get Z. I want to be able to store each of the vertices in that sequence into an array. Then place that array into a bigger list of arrays that will contain all of the sequences. The problem is that I’m not sure where to place that since the while loop below is for updating the costs of the edges.

JavaScript

Advertisement

Answer

The usual procedure is to keep track of the predecessor of each vertex. Every time you update the cost for a vertex, you store the vertex that you got there from as its predecessor.

When you’re done, you can follow the chain of predecessors from any vertex back to the source to find the shortest path to it.

Advertisement