Skip to content

743. Network Delay Time 👍

  • Time: $O(|E| + |V|\log |E|)$
  • Space: $O(|V|)$
 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
class Solution {
 public:
  int networkDelayTime(vector<vector<int>>& times, int n, int k) {
    using P = pair<int, int>;
    vector<vector<P>> graph(n);
    priority_queue<P, vector<P>, greater<>> minHeap;  // (d, u)
    vector<bool> seen(n);

    for (const auto& t : times) {
      const int u = t[0] - 1;
      const int v = t[1] - 1;
      const int w = t[2];
      graph[u].emplace_back(v, w);
    }

    minHeap.emplace(0, k - 1);

    while (!minHeap.empty()) {
      const auto [d, u] = minHeap.top();
      minHeap.pop();
      if (seen[u])
        continue;
      seen[u] = true;
      if (--n == 0)
        return d;
      for (const auto& [v, w] : graph[u])
        minHeap.emplace(d + w, v);
    }

    return -1;
  }
};
 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
class Solution {
  public int networkDelayTime(int[][] times, int n, int k) {
    List<Pair<Integer, Integer>>[] graph = new List[n];
    Queue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); // (d, u)
    boolean[] seen = new boolean[n];

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (int[] t : times) {
      final int u = t[0] - 1;
      final int v = t[1] - 1;
      final int w = t[2];
      graph[u].add(new Pair<>(v, w));
    }

    minHeap.offer(new int[] {0, k - 1});

    while (!minHeap.isEmpty()) {
      final int d = minHeap.peek()[0];
      final int u = minHeap.poll()[1];
      if (seen[u])
        continue;
      seen[u] = true;
      if (--n == 0)
        return d;
      for (var node : graph[u]) {
        final int v = node.getKey();
        final int w = node.getValue();
        minHeap.offer(new int[] {d + w, v});
      }
    }

    return -1;
  }
}