I am trying to print the shortest path for a specific adjacency matrix using dijktra's algorithm. My dijkstra algorithm works fine, I am getting the correct distances. However when printing out the path I am getting an incorrect path. Here is my code for printing the path:
My first class is my driver that takes in an adjacency matrix. The matrix contains the size at the top of the file, the actual matrix in the middle, and the source vertex at the end of the file. That all works fine for calculating the shortest distance. The following is my full code.
public void findPath(int size, int s) {
// print the path and the distance of each vertex
int j;
// iterate to find the distances
for (int i = 0; i < size; i++) {
System.out.print("[" + distance[i] + "] ");
if (i != 0) {
System.out.print(s);
j = i;
do {
j = path[j];
System.out.print(" <- " + j);
} while (j != startVertex);
}
System.out.println();
}
}
}
You have the following problems in your
findPath
method:if (i != 0)
line.do
loop instead ofwhile
, you are printing spurious "move by standing still" path steps for short paths.I haven't examined your dijkstra logic much, but these errors in combination would transform path data that matches your expected output into the observed output, so I think you're correct that the dijkstra algorithm is working properly.
Fixing most of these should be trivial, but fixing error #3 will require a minor algorithmic change - trace and reverse the path before outputting any of it.
For greater clarity, here's your original code with all the fix points marked: