PracticeNeetCode ↗LeetCode ↗
A network has n nodes labeled 1 to n, connected by directed edges with travel times. Starting a signal from node k, return the time for the signal to reach every node, or -1 if some node is unreachable.
-1.(neighbor, weight) pairs from the edge list.(0, k) and a dict recording the shortest time found for each node.(time, node); if that node's time is already recorded, skip it — it's a stale heap entry.(time + weight, neighbor) for each outgoing edge.-1.Time: O(E log E) — Space: O(V + E)
import heapq
from collections import defaultdict
def networkDelayTime(times: list[list[int]], n: int, k: int) -> int:
graph = defaultdict(list)
for u, v, w in times:
graph[u].append((v, w))
shortest = {}
min_heap = [(0, k)]
while min_heap:
time, node = heapq.heappop(min_heap)
if node in shortest:
continue
shortest[node] = time
for neighbor, weight in graph[node]:
if neighbor not in shortest:
heapq.heappush(min_heap, (time + weight, neighbor))
if len(shortest) != n:
return -1
return max(shortest.values())How the solution above works, piece by piece.
(neighbour, travel time).(0, k): the signal is at the source at time 0.shortest, a faster path got there first, so skip it. Otherwise its time is final.time + weight. Non-negative weights are what make "popped first = fastest" true.Running it on times = [[2, 1, 1], [2, 3, 1], [3, 4, 1]], n = 4, k = 2: