DSA Graphs

Network Delay Time

Dijkstra from k; the answer is the maximum shortest-path distance (or -1 if any node is unreachable).

Medium
Time O((V + E) log V) Space O(V + E)
LeetCode
7 min read
graph dijkstra shortest-path

Problem#

times[i] = [u, v, w] means an edge from u to v with travel time w. Starting at node k, return the time it takes for all n nodes to receive the signal, or -1 if some node is unreachable.

Examples#

  • times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 22
  • times = [[1,2,1]], n = 2, k = 11
  • times = [[1,2,1]], n = 2, k = 2-1

Constraints#

  • 1 <= k <= n <= 100, 1 <= times.length <= 6000, 0 <= w <= 100.

Approach#

Build the adjacency list. Run Dijkstra from k. Return the maximum distance, or -1 if any distance is INT_MAX.

Solution#

Network Delay Time
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
vector<vector<pair<int,int>>> adj(n + 1);
for (auto& e : times) adj[e[0]].push_back({e[1], e[2]});
vector<int> dist(n + 1, INT_MAX);
dist[k] = 0;
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq;
pq.push({0, k});
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (d > dist[u]) continue;
for (auto [v, w] : adj[u]) {
if (d + w < dist[v]) {
dist[v] = d + w;
pq.push({dist[v], v});
}
}
}
int ans = 0;
for (int i = 1; i <= n; ++i) {
if (dist[i] == INT_MAX) return -1;
ans = max(ans, dist[i]);
}
return ans;
}
};

Editorial#

Single-source shortest path on a non-negative-weight graph is exactly Dijkstra. The answer is the time for the last node to be reached — which is the maximum of the shortest-path distances.

Complexity#

  • Time: O((V + E) log V).
  • Space: O(V + E).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.