Skip to content

2642. Design Graph With Shortest Path Calculator 👍

  • Time: Constructor: $O(1)$, addEdge(self: List[int]): $O(1)$, shortestPath(node1: int, node2: int): $O((|V| + |E|)\log |V|)$
  • Space: $O(|V| + |E|)$
 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
class Graph {
 public:
  Graph(int n, vector<vector<int>>& edges) {
    graph.resize(n);
    for (const vector<int>& edge : edges)
      addEdge(edge);
  }

  void addEdge(vector<int> edge) {
    const int u = edge[0];
    const int v = edge[1];
    const int w = edge[2];
    graph[u].emplace_back(v, w);
  }

  int shortestPath(int node1, int node2) {
    vector<int> dist(graph.size(), INT_MAX);
    using P = pair<int, int>;  // (d, u)
    priority_queue<P, vector<P>, greater<>> minHeap;

    dist[node1] = 0;
    minHeap.emplace(dist[node1], node1);

    while (!minHeap.empty()) {
      const auto [d, u] = minHeap.top();
      minHeap.pop();
      if (u == node2)
        return d;
      for (const auto& [v, w] : graph[u])
        if (d + w < dist[v]) {
          dist[v] = d + w;
          minHeap.emplace(dist[v], v);
        }
    }

    return -1;
  }

 private:
  vector<vector<pair<int, int>>> graph;
};
 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
class Graph {
  public Graph(int n, int[][] edges) {
    graph = new List[n];
    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();
    for (int[] edge : edges)
      addEdge(edge);
  }

  public void addEdge(int[] edge) {
    final int u = edge[0];
    final int v = edge[1];
    final int w = edge[2];
    graph[u].add(new Pair<>(v, w));
  }

  public int shortestPath(int node1, int node2) {
    int[] dist = new int[graph.length];
    Arrays.fill(dist, Integer.MAX_VALUE);
    // (d, u)
    Queue<Pair<Integer, Integer>> minHeap = new PriorityQueue<>(Comparator.comparing(Pair::getKey));

    dist[node1] = 0;
    minHeap.offer(new Pair<>(dist[node1], node1));

    while (!minHeap.isEmpty()) {
      final int d = minHeap.peek().getKey();
      final int u = minHeap.poll().getValue();
      if (u == node2)
        return d;
      for (Pair<Integer, Integer> pair : graph[u]) {
        final int v = pair.getKey();
        final int w = pair.getValue();
        if (d + w < dist[v]) {
          dist[v] = d + w;
          minHeap.offer(new Pair<>(dist[v], v));
        }
      }
    }

    return -1;
  }

  private List<Pair<Integer, Integer>>[] graph;
}
 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
class Graph:
  def __init__(self, n: int, edges: List[List[int]]):
    self.graph = [[] for _ in range(n)]
    for edge in edges:
      self.addEdge(edge)

  def addEdge(self, edge: List[int]):
    u, v, w = edge
    self.graph[u].append((v, w))

  def shortestPath(self, node1: int, node2: int) -> int:
    dist = [math.inf] * len(self.graph)

    dist[node1] = 0
    minHeap = [(dist[node1], node1)]  # (d, u)

    while minHeap:
      d, u = heapq.heappop(minHeap)
      if u == node2:
        return d
      for v, w in self.graph[u]:
        if d + w < dist[v]:
          dist[v] = d + w
          heapq.heappush(minHeap, (dist[v], v))

    return -1