2642. Design Graph With Shortest Path Calculator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Graph {

private static class Edge {
private final int from;
private final int to;
private final int cost;

public Edge(int from, int to, int cost) {
this.from = from;
this.to = to;
this.cost = cost;
}
}

private final List<List<Edge>> nodeToEdgeListMap;

public Graph(int n, int[][] edges) {
// 有向带权图
nodeToEdgeListMap = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
nodeToEdgeListMap.add(new ArrayList<>());
}

for (int[] edge : edges) {
Edge e = new Edge(edge[0], edge[1], edge[2]);
nodeToEdgeListMap.get(e.from).add(e);
}
}

public void addEdge(int[] edge) {
Edge e = new Edge(edge[0], edge[1], edge[2]);
nodeToEdgeListMap.get(e.from).add(e);
}

public int shortestPath(int node1, int node2) {
int[] nodeCostMap = new int[nodeToEdgeListMap.size()];
Arrays.fill(nodeCostMap, Integer.MAX_VALUE);
nodeCostMap[node1] = 0;

// int[]: 0: node, 1: cost
Queue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o[1]));
queue.offer(new int[]{node1, 0}); // 起始节点的 cost 为 0

while (!queue.isEmpty()) {
int[] pair = queue.poll();
int node = pair[0], cost = pair[1];
if (node == node2) {
// 到达目标节点
return cost;
}

for (Edge edge : nodeToEdgeListMap.get(node)) {
if (cost + edge.cost < nodeCostMap[edge.to]) {
nodeCostMap[edge.to] = cost + edge.cost;
queue.offer(new int[]{edge.to, nodeCostMap[edge.to]});
}
}
}

return -1;
}

}

References

2642. Design Graph With Shortest Path Calculator