I need to modify Dijkstra's algorithm so that if there are several shortest paths I need to find the one with minimum number of edges on the path.
I've been stuck on how to use Dijkstra's method to find multiple shortest paths, how do you do that? doesn't it always output only 1 shortest path? pseudo code or any general direction would be very helpful.
Instead of assigning every node with the distance from source you can assign the number of edges traversed so far also. So each node will have
(distance,edges)
instead ofdistance
only. Everything else works as usual and for every terminal node you record the one with minimum value of(distance,edges)
.inspired by BlueRaja
then call updateAdjacencyMatrix() in your normal Dijkstra's implementation
We can add a very small value (let say ε) to each edge . Now the path that will have a higher number of edges will have a higher cost than the path that have lesser number of edges whereas both path had equal minimum path length.
But we need to be careful about choosing such small value, as let's say there was a path that had a higher cost previously, but a lesser number of edges, then after this value modification a previously shorter path can end up having a higher value as the number of ε added to it is higher .
Proof - Let's say the graph has n edges. And it’s the shortest path contains (n-1) edges which is slightly high (this value will at least be the difference between 2 minimum edge ) than another path having just 1 edge. So after adding ε to all the edges, the minimum path is still minimum as at least (n+1) epsilon to make it longer than the other path, but it just has (n-1) ε. After value modification apply Dijkstra's algo to find the shortest path between s and t.
Here is the python code -
Maintain minPathLen field for each vertex for dijktra.
And in loop where you compare
Add another statement:-
Another option would be to add some small number
ε
to the weight of every edge, whereε << edgeWeights
(for integer edge-weights you can chooseε < gcd(edgeWeights)/numberOfEdges
)The advantage of this approach is that you don't need to write your own pathfinder, you can just use any off-the-shelf implementation.