右边是老师写好用于上课演示的代码该程序创建一个有向图确定一个起点然后计算从起点出发到达所有顶点的最短距离文件已经写好了但是只有一个问题:那就是程序输出的结果不正确请帮助老师找到程序代码的BUG在哪里并修改成正确的程序代码程序的测试输入如下: ShortestPathSolution sln = new ShortestPathSolution; int edges = 122 1581
修改后的代码如下:
public class ShortestPathSolution { public int[] findAllShortestPath(int n, int[][] edges, int src) { int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); dist[src-1] = 0; List<int[]>[] graph = new List[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<>(); } for (int[] edge : edges) { int u = edge[0]-1, v = edge[1]-1, w = edge[2]; graph[u].add(new int[] {v, w}); } PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); pq.offer(new int[] {src-1, 0}); while (!pq.isEmpty()) { int[] curr = pq.poll(); int u = curr[0], d = curr[1]; if (d > dist[u]) continue; for (int[] next : graph[u]) { int v = next[0], w = next[1]; if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; pq.offer(new int[] {v, dist[v]}); } } } return dist; } }
主要的问题在于在创建图的时候,没有考虑到有向边的方向,导致最短路径计算错误。修改后,在添加边时,需要将边的起点和终点反过来,即将原来的
graph[u].add(new int[] {v, w});
改为
graph[v].add(new int[] {u, w});
这样可以保证边是从起点指向终点的,也就是符合题目要求的有向边
原文地址: https://www.cveoy.top/t/topic/hm3p 著作权归作者所有。请勿转载和采集!