[英]Shortest Path Dijkstra Java
I am trying to print the shortest path for a specific adjacency matrix using dijktra's algorithm. 我正在尝试使用dijktra的算法为特定的邻接矩阵打印最短路径。 My dijkstra algorithm works fine, I am getting the correct distances. 我的dijkstra算法工作正常,我得到了正确的距离。 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: findPath
方法中存在以下问题:
if (i != 0)
line. 您无缘无故地使用if (i != 0)
跳过输出。 do
loop instead of while
, you are printing spurious "move by standing still" path steps for short paths. 通过使用do
循环而不是while
,您可以为短路径打印虚假的“静止不动”路径步骤。 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. 我没有仔细检查过dijkstra逻辑,但是这些错误结合在一起会将与您的预期输出匹配的路径数据转换为观察到的输出,因此我认为dijkstra算法正常工作是正确的。
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. 修复其中的大多数问题并不容易,但是修复错误#3将需要进行较小的算法更改-在输出任何路径之前先跟踪并反转路径。
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.