Problem 597059 · medium · Level 05 Advanced Algorithms & Graphs

Alert Through the Relay Towers

dijkstra · shortest path · weighted graphs · heapq

BFS finds shortest paths only when every edge costs the same. With weighted edges you need Dijkstra: always expand the closest not-yet-settled node, which a heap hands you in O(log V).

Radio relay towers are labelled 1 .. n. Each entry [u, v, w] in times is a one-way link: a message sent from tower u reaches tower v after w time units. A storm alert starts at tower k, and every tower passes it on the moment it arrives. Write network_delay_time(times, n, k) that returns how long it takes until every tower has the alert, or -1 if some tower never gets it.

Examples

Input:  times = [[3, 1, 2], [3, 2, 5], [1, 2, 1], [2, 4, 3]], n = 4, k = 3
Output: 6
Explanation: tower 2 hears sooner via 3 -> 1 -> 2 (time 3) than directly (time 5), so tower 4 hears at 3 + 3 = 6

Input:  times = [[2, 1, 7]], n = 2, k = 1
Output: -1
Explanation: the only link runs from tower 2 to tower 1, so tower 2 never hears

Constraints

  • 1 <= n <= 100, 1 <= k <= n, 1 <= w <= 100
  • All edge weights are positive (Dijkstra requires this)
  • Target: O(E log V) time

Goals

  • Implement Dijkstra's algorithm with a min-heap of (distance, node) pairs
  • Skip stale heap entries instead of trying to decrease keys
  • Handle unreachable nodes in a shortest-path computation
Starting Python…