问题
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();
}
}
}
回答1:
You have the following problems in your findPath
method:
- You are skipping output for no reason with the
if (i != 0)
line. - Your data is in the form of 0-based indices, and your desired output is 1-based, and you aren't converting between them.
- You are outputting data in the opposite order of what you want, printing the path's starting point first when your expected output puts the starting point last.
- By following one step in the path before printing anything, you are skipping the path's first step.
- By using a
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:
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] + "] ");
// FIX #1: Remove this if statement
if (i != 0) {
System.out.print(s);
j = i;
// FIX #5: Use while instead of do
do {
// FIX #4: swap the order of these two lines
j = path[j];
// FIX #2: print j+1, not j
// FIX #3: Instead of print, push onto a stack
System.out.print(" <- " + j);
} while (j != startVertex);
// FIX #3: Put your pop-and-print loop here. It should not
// involve i, and should end when the stack is empty, not
// any other condition.
}
System.out.println();
}
}
}
来源:https://stackoverflow.com/questions/35733833/shortest-path-dijkstra-java