import javautilArrays;public class ShortestPathSolution static final int RED = 2; static final int GREEN = 1; static final int WHITE = 0; public int findAllShortestPathint n int edges int
修改后的代码如下:
import java.util.Arrays;
public class ShortestPathSolution {
static final int RED = 2;
static final int GREEN = 1;
static final int WHITE = 0;
public int[] findAllShortestPath(int n, int[][] edges, int src) {
int[] dist = new int[n + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
int[] visit = new int[n + 1];
visit[src] = GREEN;
dist[src] = 0;
for (int i = 0; i < n - 1; i++) { // 修改循环次数,应为n-1
int s = 0;
for (int j = 1; j <= n; j++) {
if (visit[j] == GREEN && (s == 0 || dist[j] < dist[s]))
s = j;
}
if (s == 0) break;
visit[s] = RED;
for (int[] ed : edges) {
int u = ed[0], v = ed[1], w = ed[2];
if (s == u && visit[v] != RED) {
int d = dist[s] + w;
if (d < dist[v]) {
dist[v] = d;
visit[v] = GREEN;
}
}
}
}
System.out.println("所有的顶点路径信息:");
for (int i = 1; i <= n; i++)
System.out.println("目标顶点 " + i + " -> " + dist[i]);
return dist;
}
}
主要修改了循环次数,原程序中的循环次数为n,而应该是n-1,因为最短路径最多经过n-1条边
原文地址: https://www.cveoy.top/t/topic/hm9u 著作权归作者所有。请勿转载和采集!