With Dijkstra you use the end-condition
while(!q.isEmpty()){
//Some code
}
But if you know the end node, is it not possible to change the end-condition to
while(!q.peek().equals(endNode){
//Some code
}
Every implementation of Dijkstra I have seen uses the earlier, but the later is faster when you know the end node. Or is this not Dijkstra anymore?
Depends on what you want the algorithm to do. The original Dijkstra's algorithm computes the length of the shortest path from the source to each other vertex. If you have a single target vertex, you can cut the algorithm short after you've popped the target off the queue.
Correctness of the shortcut can be easily proven: Dijkstra's never changes the shortest-path length of a node that it has already popped off the queue, so you know you're looking at the length it would return if you continued running the algorithm until the queue was empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With