Code of the Day
AdvancedAdvanced Graphs

Dijkstra's algorithm

Implement Dijkstra's algorithm with a min-heap to find shortest distances from a source, then reconstruct the full path.

CS FundamentalsAdvanced12 min read
Recommended first
By the end of this lesson you will be able to:
  • Implement Dijkstra's algorithm using heapq
  • Return shortest distances from a source node to all reachable nodes
  • Reconstruct the shortest path using a predecessors dict

Dijkstra's algorithm extends the relaxation idea from the previous lesson into a complete algorithm. The key guarantee: always relax from the node with the currently smallest known distance. A min-heap (priority queue) enforces that ordering efficiently.

The algorithm

  1. Initialise dist[source] = 0, dist[v] = ∞ for all other nodes.
  2. Push (0, source) onto a min-heap.
  3. Pop the cheapest (d, u). If d > dist[u], this is a stale entry — skip it.
  4. For each neighbour (v, w) of u, relax: if dist[u] + w < dist[v], update dist[v] and push (dist[v], v) onto the heap.
  5. Repeat until the heap is empty.

The "stale entry" check replaces the need to update existing heap entries (which is expensive). Push a new entry instead; when you pop the stale one, discard it.

Implementation

Python — editable, runs in your browser

Complexity

OperationCost
Each node popped from heapO(log V)
Each edge relaxedO(log V) for the push
TotalO((V + E) log V)

This beats Bellman-Ford's O(VE) whenever the graph is sparse (E is not much larger than V).

Dijkstra's requires all edge weights to be non-negative. A single negative edge can cause it to miss the true shortest path because it commits to a "cheapest so far" without expecting prices to drop further. For negative weights, use Bellman-Ford instead.

Reconstructing the path

The pred dict records, for each node, which node we came from on the cheapest known path. To recover the path to a target, walk backwards through pred until you reach None (the source has no predecessor), then reverse.

If pred[target] is still None and target != source, the node is unreachable — return an empty list.

Where to go next

Next: topological sort — ordering nodes in a directed acyclic graph so every edge points "forward." A key tool for build systems, course prerequisites, and any domain with dependency ordering.

Finished reading? Mark it complete to track your progress.

On this page