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

岁酱吖の 提交于 2019-12-05 10:50:14

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.

After visiting B, the total distance travelled so far is 12. 7 is smaller than 12, and hence the search will resume at C.

A node is only marked visited after all its neighbours have been considered. In the beginning, the origin is marked as visited and is assigned a distance of zero. All the other nodes are marked unvisited.

Then it picks the neighbour with the current shortest path.

No, it picks the unvisited node with the current shortest path.

Wikipedia writes:

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

It doesn't say it is a neighbor.

And the pseudocode from Wikipedia says:

 8      while Q is not empty:                  // The main loop
 9          u := vertex in Q with smallest distance in dist[] ;

where Q contains all nodes that have not yet been visited.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!