DIJKSTRA'S ALGORITHM

Greedy shortest paths, and the one assumption that makes greedy safe

L215 MINALGORITHMS
PREDICT

Directed graph: S→A 2, S→B 4, B→A −3. Textbook Dijkstra from S: each round it extracts the closest node from a priority queue, marks it final and never updates it again. What does it report for A?

Dijkstra finds shortest paths from one source in a weighted graph. It keeps a min-priority queue of tentative distances. Each round it extracts the closest node that is not yet final, marks it final, and relaxes its out-edges: if going through it makes a neighbour cheaper, it lowers that neighbour’s distance and pushes it.

Finalizing is a bet. It is safe only when no edge weight is negative, because then no later path can come back cheaper. One negative edge and the bet can lose. Versions with no final set, which re-push any node that gets cheaper, survive this small graph, but with negative edges they can take exponential time. Bellman-Ford makes no bet: it relaxes every edge V−1 times and only then calls anything final.

▶ SIMULATION
NOT STARTED dist
S: ∞ · true 0
A: ∞ · true 2
B: ∞ · true 4
C: ∞ · true 3
D: ∞ · true 5
MIN-PRIORITY QUEUE
empty
FINALIZED, IN ORDER
—
GRAPH
directed, source S
B→A = 3
missed relaxations: 0
edgesS→A 2, S→B 4, A→C 1, A→D 3, B→C 5, C→D 2, B→A 3
last stepdirected graph loaded
✓ every finalized distance is the true shortest distance
SCHEDULE
01[GRAPH]use B→A = W from the slider
02[DIJKSTRA]dist[S] = 0, push (0, S)
03[DIJKSTRA]extract-min #1, finalize it, relax its out-edges
04[DIJKSTRA]extract-min #2, finalize it, relax its out-edges
05[DIJKSTRA]extract-min #3, finalize it, relax its out-edges
06[DIJKSTRA]extract-min #4, finalize it, relax its out-edges
07[DIJKSTRA]extract-min #5, finalize it, relax its out-edges
08[GRAPH]report
Start of dijkstra, b→a = w scenario. 8 steps.
// Dijkstra: correct only if every edge weight is >= 0
dist[s] = 0; pq.push(0, s)
while pq not empty:
  u = pq.extractMin()            // greedy: u is final NOW
  if final[u]: continue          // stale entry
  final[u] = true
  for (u, v, w) in out(u):
    if !final[v] and dist[u] + w < dist[v]:
      dist[v] = dist[u] + w; pq.push(dist[v], v)
// a later negative edge into u cannot be taken back
// O((V + E) log V) with a binary heap

Watch the invariant strip in DIJKSTRA, B→A = −3. It turns red the moment A is finalized at 2, long before Dijkstra sees B→A, and C and D inherit the error. Bellman-Ford on the same graph finalizes nothing until the end and gets all five right. On the negative-cycle graph it finalizes nothing at all and says why.

BREAK IT NOT YET

Drag the weight of the single edge B→A. Find a value where Dijkstra finishes with a finalized distance that is wrong. Notice which negative values it survives.

GOAL: Dijkstra finishes with at least one wrong finalized distance

FIX IT NOT YET

This version takes nodes from the queue in the order they were added, not by distance, so it finalizes nodes too early even with non-negative weights. Make each iteration finalize the closest unfinalized node. The grader compares your distances with a Bellman-Ford reference on several directed graphs and checks that each node’s out-edges are scanned once, after it is final.

Mental model:

Dijkstra is a wavefront: the queue’s minimum is the next node the wave reaches, and it is final because nothing behind the wave can get cheaper. That holds only with non-negative weights. A negative edge lets a later path undercut a closed node. If weights can go negative, use Bellman-Ford, which delays every decision until all V−1 rounds of relaxation are done and can detect a negative cycle.

IN PRODUCTION

Link-state routing (OSPF and IS-IS run Dijkstra over link costs, which are positive by design), map routing, network latency graphs, dependency costs in build systems. The bug shows up when someone adds a discount, rebate or credit as a negative edge.

IN INTERVIEWS

“Implement shortest path in a weighted graph” and the follow-up “what if weights can be negative?” Explain why the extracted node is final, give the three-node counterexample, name Bellman-Ford and its O(V·E) cost, and say how the extra pass detects a negative cycle.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: A* SEARCH →