8

In Dijkstra's algorithm what should I do if there are two or more nodes with minimal weights at a point in the algorithm?

In wikipedia: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm at step no. 6, it says

"Set the unvisited node marked with the smallest tentative distance as the next 'current node' and go back to step 3."

What if there are two or more nodes with "smallest tentative distance".

Can anyone help me with the algorithm?

coolscitist
  • 3,317
  • 8
  • 42
  • 59

1 Answers1

3

Short Answer

Just pick either. Unless you have another heuristic to work with, you can't tell which would be better to pick.


Bit More Explaination

Think about sorting some elements into an array:

9 6 3 3 8

sorted with lowest first is

3 3 6 8 9

If you were to query that array to determine the lowest, the answer is 3. Which 3 doesn't matter.


Similarly if you were to have some more information. Say for example that those ints were actually floats and were sorted by their integer parts. You might end up with the array:

3.2  3.1  6.0  8.5  9.2

Here you have another heuristic to work with, you can check the decimal part too, and you can determine that 3.1 is the lowest.

James Webster
  • 31,873
  • 11
  • 70
  • 114
  • 1
    If I choose any one of them, then I might not get the path with minimum weight. So, I was actually thinking of choosing all those "minimum weight" nodes as "current" nodes. Then I would choose the node which gives the minimum weight in the next phase as the "visited" node. However, even in that next phase, there could still be two or more nodes with minimum weight. So, most probably, a recursive algorithm would be required. – coolscitist Feb 13 '12 at 17:38
  • I have accepted the answer. However, other suggestions are welcome too. – coolscitist Feb 13 '12 at 17:40
  • Dijkstra's algorithm revisits old nodes, so it should return the optimal path if it 'finds' that it chose a wrong node earlier. – James Webster Feb 13 '12 at 17:42
  • I am trying reach from one source node to a target node. When I used the algorithm (just as stated in wikipedia), it did not give me the optimal path. Actually, when I got to the target node, and I found it to be optimal in comparison to the rest of the nodes, I stopped the algorithm. – coolscitist Feb 14 '12 at 02:58
  • So, it 'did not' find that it chose the wrong node. So that may be why the path was not optimal. Anyway, thanks for the clarification. – coolscitist Feb 14 '12 at 03:00