【发布时间】:2015-11-19 10:35:08
【问题描述】:
我想使用 Floyd-Warshall 算法来找到两个顶点之间的最短路径。该矩阵位于 ArrayList
在我的课堂上,我已经有了一个距离矩阵。我只是想创建“最短路径”矩阵。但它不起作用。它错误地填充了我的矩阵。
我真的希望有人能看看这个并解释问题所在。
我的距离矩阵是:
0 0 256 411
556 0 558 0
250 0 0 431
0 0 431 0
测试输出为:
0 0 0 0
556 556 556 556
250 250 250 250
0 0 0 0
预期:
500 0 842 681
556 0 806 967
0 0 500 681
581 0 0 862
我已经注释掉了我的测试输出。 distance 是我的矩阵,具有顶点之间距离的整数值。在我的矩阵中,i 是 y,j 是 x。
public ArrayList<ArrayList<Integer>> calcShortest() {
//String test = "";
ArrayList<ArrayList<Integer>> shortest = distance;
for (int k = 0; k < airports.size(); k++) {
for (int i = 0; i < airports.size(); i++) {
for (int j = 0; j < airports.size(); j++) {
shortest.get(j).add(i, Math.min(shortest.get(k).get(i) + shortest.get(j).get(k),
shortest.get(j).get(i)));
}
}
}
/*for (int j = 0; j < airports.size(); j++) {
for (int i = 0; i < airports.size(); i++) {
test += shortest.get(j).get(i) + " ";
}
System.out.println(test);
test = "";
}*/
return shortest;
}
【问题讨论】:
-
我不知道什么是 Floyd Warshall 算法,但你能告诉我们如何使用基本操作得到预期的矩阵吗?
-
维基百科:“Floyd–Warshall 算法是一种在加权图中寻找最短路径的算法”,因此它会填充最短路径,例如它会检查从 a 到 c 的最短路径,当有一条可行的路径时,它会发现它更快地越过 d 而不是 b 并且将填充最短距离。我使用的是有向图,所以这就是为什么它一开始看起来很奇怪。
标签: java algorithm matrix floyd-warshall