SkyWalker
SkyWalker

Reputation: 14309

Algorithms in Java from Prim's MST to Dijkstra SPT

I am following the code of the Algorithms in Java, Part 5: Graph Algorithms, 3rd Edition book and in page 294 it describes that we can have the classic Dijkstra algorithm by modifying Prim's Minimum Spanning Tree (MST) algorithm (which I tested and works fine) in the following way: change the priority assignment from P = e->wt() the edge weight to P = wt[v] + e->wt() the distance from the source to the edge’s destination. The problem is that when I make the change the condition that follows never evaluates to true and it is understandably so. wt is a double array initialized to e.g. Double.MAX_VALUE therefore no matter what v and w are, this condition will never hold (assuming non negative weights):

P = wt[v] + e->wt();
if (P < wt[w]) { // this can never happen ... bug?
   // ...
} 

I checked the web site of the book and see no errata.

This is my self contained version of the code with a runnable Main with the test case from the book:

UPDATES:

Upvotes: 2

Views: 1177

Answers (1)

kutschkem
kutschkem

Reputation: 8163

You get it wrong, since v != w, wt[v] + e->wt() can be smaller than wt[w]. The actual error is that you need to set wt[source] = 0 (dijkstra is single-source shortest path, you need a source!) ! About the book: if they forgot that part, their bad :-P

Upvotes: 1

Related Questions