Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dijkstras Algorithm doesn't appear to work, my understanding must be flawed

Here's my interpretation of how Dijkstra's algorithm as described by wikipedia would deal with the below graph.

First it marks the shortest distance to all neighbouring nodes, so A gets 1 and C gets 7. Then it picks the neighbour with the current shortest path. This is A. The origin is marked as visited and will not be considered again. The shortest (and only) path from the origin to B through A is now 12. A is marked as visited. The shortest path from the origin to the Destination through B is 13. B is marked as visited. The shortest path from the Origin to C through the destination is 14, but this is double the previous shortest path to C, which is 7, so the 14 is discarded. The destination is now marked as visited.

Destination has been marked visited, therefore the alogorithm is complete. Here's the result:

Supposedly failing case for Dijkstra

So am I misinterpretting the description? Is the description on wikipedia wrong? Or have I somehow stumbled upon a case that shows Dijkstra's algorithm is incorrect (which I highly doubt)? I've noticed that the path chosen seems to be picked in a greedy manner, but apparently this is one of the defining characteristics of the algorithm, however in this case it seems to give the wrong result.

like image 455
TheIronKnuckle Avatar asked Dec 21 '11 23:12

TheIronKnuckle


1 Answers

Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes called the unvisited set consisting of all the nodes except the initial node. (Wiki)

Using your example:

Unvisited

A = inf;
B = inf;
C = inf;
Dest = inf;

Visited

Origin = 0;

For the current node, consider all of its unvisited neighbors and calculate their tentative distances.

O => A = 1;
O => C = 7;

We are now at A.

From A, the only path is B, this gives us

O => AB = 12;
O => C = 7

C is now lowest distance, and is the new current node

O => CD = 8

Since D is destination and 8 < 12, the route CD is chosen.

like image 69
KingCronus Avatar answered Nov 15 '22 10:11

KingCronus