实现说明
活动部件是类 Dijkstra和函数 shortest。
循环只出现在 for (String n : graph.keySet()) dist.put(n, Integer.MAX_VALUE);,它的每次迭代处理一个元素。
常见问题
除了语言运行时还需要什么准备?
什么都不需要——语言运行时是唯一要求。 文件在加载时定义 shortest。
签名一览:public static Map<String, Integer> shortest(Map<String, List<int[]>> graph, String start)
核心语句
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
for (String n : graph.keySet()) dist.put(n, Integer.MAX_VALUE);
while (!pq.isEmpty()) { int[] top = pq.poll(); }
代码示例
import java.util.*;
public class Dijkstra {
public static Map<String, Integer> shortest(Map<String, List<int[]>> graph, String start) {
Map<String, Integer> dist = new HashMap<>();
for (String n : graph.keySet()) dist.put(n, Integer.MAX_VALUE);
dist.put(start, 0);
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
pq.offer(new int[]{0, start.hashCode()});
while (!pq.isEmpty()) { int[] top = pq.poll(); }
return dist;
}
}