Network Delay Time
Master this topic with zero to advance depth.
Network Delay Time
You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (u_i, v_i, w_i), where u_i is the source node, v_i is the target node, and w_i is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.
Visual Representation
Nodes: 4, Times: [[2,1,1],[2,3,1],[3,4,1]], K: 2
(1) <--1-- (2) --1--> (3) --1--> (4)
Signal at 2 reaches 1 and 3 at T=1.
Signal reaches 4 at T=2.
Result: 2Examples
Signal reaches all nodes in 2 units of time.
Level I: Brute Force (Bellman-Ford)
Intuition
Bellman-Ford is a simpler shortest path algorithm that works by repeatedly relaxing all edges. After iterations, all shortest paths are guaranteed to be found.
Thought Process
- Initialize
distarray with infinity,dist[k] = 0. - For iterations:
- For each edge in
times:- If
dist[u] + w < dist[v], updatedist[v] = dist[u] + w.
- If
- For each edge in
- After iterations, check
max(dist). If any node is still at infinity, return-1.
Why it's Level I
It is computationally slower than Dijkstra but much simpler to implement correctly as it doesn't require a priority queue.
Detailed Dry Run
n=4, k=2, edges=[[2,1,1],[2,3,1],[3,4,1]]
- Init: dist=[inf, 0, inf, inf] (using 1st index for node 1)
- Iter 1:
- edge (2,1,1): dist[1]=1
- edge (2,3,1): dist[3]=1
- edge (3,4,1): dist[4]=1+1=2
- Iter 2 & 3: No changes. Max dist = 2
Level III: Optimal (Dijkstra's Algorithm)
Intuition
This is a single-source shortest path problem on a weighted graph with non-negative weights. Dijkstra's algorithm uses a priority queue to always expand the node with the smallest known distance.
Thought Process
- Build an adjacency list:
u -> (v, w). - Initialize a
distarray with infinity,dist[k] = 0. - Use a Min-Priority Queue to store
(time, node)pairs. - While the queue is not empty:
- Pop
(t, u). Ift > dist[u], continue (stale entry). - For each neighbor
(v, weight)ofu:- If
dist[u] + weight < dist[v]:- Update
dist[v] = dist[u] + weightand push to queue.
- Update
- If
- Pop
- The answer is
max(dist). If any node is unreachable (infinity), return-1.
Pattern: Shortest Path (Dijkstra)
Detailed Dry Run
n=4, k=2, edges=[[2,1,1],[2,3,1],[3,4,1]]
| PQ (t,u) | dist[] | Action |
|---|---|---|
| (0,2) | [inf, 0, inf, inf] | Init |
| (1,1), (1,3) | [1, 0, 1, inf] | Pop 2, relax 1 & 3 |
| (1,3) | [1, 0, 1, inf] | Pop 1 |
| (2,4) | [1, 0, 1, 2] | Pop 3, relax 4 |
| Max(dist) = 2 |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.