6

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?

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
SBylemans
  • 1,764
  • 13
  • 28

1 Answers1

14

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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • Yeah, I have a single target vertex. But is this still a correct implementation of Dijkstra, or could it be ruled that this isn't Dijkstra anymore? – SBylemans May 28 '14 at 08:59
  • 1
    @Rednas That's really just a matter of terminology. Dijkstra's algorithm exists in several variants, and the basic properties including worst-case complexity are unchanged when you stop the algorithm early. – Fred Foo May 28 '14 at 09:18
  • Ok thanks, I executed with the later condition and the time of execution is aprox cut in half :p – SBylemans May 28 '14 at 09:33
  • I thought it can requeue the vertex if there is another path? And if you end it early, doesn't this mean you can potentially miss out on another path that might be even shorter? – Strawberry Nov 18 '18 at 05:11
  • 1
    @Strawberry I had the same question but I think not, since the queue orders vertices from least to greatest distance from the start vertex. Say Z is the end vertex and at the top of the queue with a value of 30. Y is below it in the queue and links to Z. But this path is always >= 30, otherwise Y would be above Z in the queue. So safe to end early. – branweb Dec 13 '18 at 03:14