Advanced Graphs
Weighted edges: Dijkstra always grows the shortest known path next, using a min-heap of distances.
Spot it
Signals in the questionEdges have weights (time, cost, distance) and you want the cheapest path.
"How long until the signal reaches every node?"
Connect everything for the least cost: minimum spanning tree (Prim / Kruskal).
The idea
O(E log V) time · O(V + E) spaceStart with the source at distance 0. Repeatedly take the closest node you haven't settled; its distance is now final. Relax its edges: if going through it is shorter, update the neighbour. A min-heap finds the closest node fast.
Template · Dijkstra
1import heapq23def network_delay(times, n, k):4 graph = {i: [] for i in range(1, n + 1)}5 for u, v, w in times:6 graph[u].append((v, w))7 dist, heap = {}, [(0, k)]8 while heap:9 d, node = heapq.heappop(heap) # closest not yet settled10 if node in dist:11 continue12 dist[node] = d13 for nxt, w in graph[node]:14 if nxt not in dist:15 heapq.heappush(heap, (d + w, nxt))16 return max(dist.values()) if len(dist) == n else -1
The template, filled in for Network Delay Time. The highlighted lines are the part every problem of this kind shares.
The best, free
One of eachPractice set
Loading your mission…
Common mistakes
1Using Dijkstra with negative edge weights: it can settle a node too early.
2Settling a node more than once: skip heap entries for nodes already done.
3Forgetting unreachable nodes: the answer may be -1.
Check yourself
Question 1 of 2Why does Dijkstra take the closest unsettled node first?