TRACK B · ALGORITHMmedium•NOVEMBER 2026•7 MIN
Dijkstra's Algorithm: Weighted Shortest Paths
Swap BFS's queue for a min-heap to find minimum-latency routes across non-negative weighted networks.
dijkstraheapgraphsshortest-pathweighted-graph
The core idea
When edges have different non-negative costs (like fiber latencies in ms), fewer hops no longer means faster. Always expand the globally closest unfinalized node from a min-heap.
Watch it run
Step through the trace below (or turn on Predict Mode) to watch the invariant hold at every step.
LOADING DIJKSTRA WEIGHTED GRAPH SIM...
What to say out loud
Canonical Python template
import heapq
def dijkstra(adj: dict[str, list[tuple[str, int]]], start: str) -> dict[str, int]:
best = {start: 0}
pq = [(0, start)]
while pq:
d, u = heapq.heappop(pq)
if d > best[u]:
continue
for v, w in adj[u]:
if d + w < best.get(v, float("inf")):
best[v] = d + w
heapq.heappush(pq, (d + w, v))
return best