Module A-6·14 min read

Single-source shortest path with a min-heap — the algorithm behind every non-negative-weight routing problem.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

Module A-6 — Shortest Paths I: Dijkstra's Algorithm

What this module covers: Module A-5's BFS finds shortest paths measured in hop count — correct only when every edge costs the same. This module covers the weighted version: Dijkstra's algorithm, which is BFS with one structural swap — Module A-1's min-heap standing in for Module F-7's plain queue — always processing whichever unvisited node currently has the smallest known total distance, not just whichever was enqueued first.


Why BFS Breaks on Weighted Graphs

BFS's shortest-path guarantee (Module A-5) depends entirely on every edge costing exactly the same "1 hop." On a weighted graph, a path with fewer edges can easily cost more than a path with more edges that are individually cheaper — Module P-6 already flagged this exact failure mode. Dijkstra's algorithm fixes it by tracking actual accumulated cost, not hop count, and by always expanding outward from whichever reachable node currently has the smallest known cost — not whichever was simply discovered first.


The Algorithm: BFS With a Min-Heap Instead of a Queue

typescript

Compare this line-by-line against Module A-5's shortestPathLength: same overall shape (extract a node, look at its neighbors, push newly-discovered or improved distances), but Module F-7's plain FIFO queue is replaced by Module A-1's min-heap, and instead of tracking "distance = hop count," distances tracks actual accumulated edge weight. Always extracting the minimum is what makes this correct: once a node is popped from the min-heap, no undiscovered path could possibly reach it more cheaply, because every alternative path would have to go through some other node whose distance is at least as large as what's currently at the top of the heap — there's nothing left in the heap with a smaller distance that could somehow produce a shorter route.


Why This Only Works With Non-Negative Weights

The correctness argument above — "no path through a not-yet-processed node could possibly be cheaper" — depends entirely on edge weights never being negative. If a negative edge existed, a longer-looking path that later dips through a large negative weight could end up cheaper than a path Dijkstra already finalized and moved past, and Dijkstra has no mechanism to revisit a node it's already marked visited and committed to.

typescript

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.