The problem
Given a graph whose edges carry non-negative weights and a source node s, find for every node
v the cost of the cheapest path from s to v, and a path that achieves it. Weights can mean
metres, milliseconds or money; what matters is that walking an edge never makes a path cheaper.
Breadth-first search already solves this when every edge costs the same: it reaches nodes in order of their hop count. Dijkstra's algorithm is the generalisation to unequal weights. Instead of a FIFO queue it uses a priority queue keyed by distance, so it always continues from the closest node it has not finished yet.
Two tables and one operation
The algorithm keeps two arrays indexed by node:
dist[v]: the cost of the best path tovfound so far (∞ until one is found).prev[v]: the node just beforevon that path (none for the source and for unreached nodes).
Everything changes through one operation, relaxing an edge u → v with weight w:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
prev[v] = u
"Going through u is cheaper than anything we knew for v, so remember that." Relaxation never makes
dist[v] wrong in the unsafe direction: every value it stores is the length of a real path, so
dist[v] is always an upper bound on the true distance. The algorithm's job is to relax edges
in an order that drives each upper bound down to the truth, and to know when that has happened.
The algorithm
dist[*] = ∞, prev[*] = none
dist[s] = 0
push (0, s) onto a min-heap
while the heap is not empty:
(d, u) = pop the smallest entry
if d > dist[u]: continue # stale entry, skip it
# dist[u] is now final: u is "settled"
for each edge u → v with weight w:
if d + w < dist[v]:
dist[v] = d + w
prev[v] = u
push (dist[v], v)
The lab runs exactly this. The ring of nodes shows d= tags (∞ until reached), settled nodes in green
and the shortest-path tree in teal; the lane in front is the heap in array order, minimum first.
Lazy deletion
When a shorter path to v turns up, v may already have an entry in the heap with its old, larger
distance. The textbook remedy is a decrease-key operation that finds that entry and lowers it.
None of the four standard libraries offers one, so the implementations here use lazy deletion:
push a second entry with the new distance and leave the old one where it is. The new entry pops
first, because it is smaller. When the old one finally pops, d > dist[v] gives it away as stale and
the loop skips it.
In the Six nodes, a stale entry preset, node 1 is first reached directly at cost 4, then through
node 2 at cost 1 + 2 = 3. The heap briefly holds both (4, 1) and (3, 1); the lab greys out the
stale one, and the Stale skips metric counts it when it is popped and ignored.
The price is a larger heap: up to one entry per successful relaxation instead of one per node. That changes the constant inside the logarithm, not the bound (see below).
Determinism and ties
Two different nodes can have the same distance. The heap entries here are pairs (distance, node)
compared lexicographically, so equal distances pop the smaller node first. Relaxation uses a
strict <, so when a second path ties the best known one, the first predecessor found stays.
Neighbours are scanned in the order the edges were given. With these three rules, the settle order,
the stale-entry count and prev[] are identical in the lab and in all four languages, which is what
lets one fixture check them all. The Ties and zero weights preset shows nodes 1 and 2 at distance 1
leaving the heap in id order.
Shortest distances never depend on tie-breaking; shortest paths can, when several exist.
Why a popped distance is final
Claim. When a node u is popped with d = dist[u] (not stale), dist[u] equals the true
shortest distance δ(u).
Sketch. Suppose not, and let u be the first node settled with dist[u] > δ(u). Take a real
shortest path from s to u. It starts inside the settled set (at s) and ends outside it (at u),
so it has a first node y that is not settled yet, whose predecessor x on the path is settled.
When x was settled, the edge x → y was relaxed, and x's distance was already correct (u is the
first failure), so dist[y] = δ(y) and y has a heap entry with that value. Because weights are
non-negative, the rest of the path from y to u costs at least 0, so δ(y) ≤ δ(u) < dist[u]. The
heap would therefore pop y's entry before u's. Contradiction.
The step that needs non-negative weights is "the rest of the path costs at least 0". That is the whole reason for the restriction, and it is why the lab and every implementation reject negative weights instead of returning something plausible.
What goes wrong with a negative edge
Take edges s → a (2), s → b (5), b → a (−4). The heap pops a at distance 2 and declares it
final, but s → b → a costs 1. A version that marks nodes as visited and never revisits them
returns 2 for a, and every distance computed from a is wrong too. The lazy version would notice
the improvement and push a again, but then the argument above no longer holds, nodes can be
processed many times, and on adversarial graphs the work grows exponentially. For negative weights
use Bellman-Ford (O(V·E), and it detects negative cycles); for a DAG, relax in topological order.
Complexity
Let V be the number of nodes and E the number of edges.
- Each node is settled at most once, and its outgoing edges are scanned then: O(V + E) relaxation checks in total (an undirected edge is checked from both ends).
- Each successful relaxation pushes one entry, so there are at most E + 1 pushes and as many pops. (An undirected edge is checked from both ends but can succeed only from the endpoint settled first.)
- With a binary heap holding at most E + 1 entries, each push or pop costs O(log E). Since E ≤ V², log E ≤ 2 log V, so O(log E) = O(log V).
| Version | Time | Extra space |
|---|---|---|
| Binary heap, lazy deletion (this lesson) | O((V + E) log V) | O(V + E): tables plus up to E + 1 heap entries |
| Binary heap with decrease-key | O((V + E) log V) | O(V): one entry per node, plus a position index |
| Unsorted array, scan for the minimum | O(V² + E) | O(V) |
| Fibonacci heap (theoretical) | O(E + V log V) | O(V) |
On a dense graph (E close to V²), the simple array version's O(V²) beats O((V + E) log V) = O(V² log V); the heap wins on sparse graphs such as road networks, where E is a small multiple of V. Fibonacci heaps have the best bound, but their constants rarely pay off in practice.
These bounds assume adjacency lists. With an adjacency matrix, scanning the neighbours of one node costs O(V) whatever its degree, so the total is at least O(V²).
Reconstructing the path
prev[] stores a tree: every reached node points to its predecessor on one shortest path, and the
source is the root. To get the path to a target t, follow prev from t until there is no
predecessor, then reverse:
if dist[t] == ∞: return [] # unreachable
path = []
v = t
while v is not none:
path.append(v)
v = prev[v]
reverse(path)
That costs O(length of the path). The lab ends each run with this walk, highlighting the path in green. In the Directed, one unreachable node preset node 4 has an edge into the graph but none reaching it from the source, so its distance stays ∞ and asking for its path returns nothing.
If you only need one target, you may stop as soon as that target is popped (not when it is first reached: it can still improve until it is settled). The implementations here run to completion so they return every distance.
The teaching implementation
Dijkstra.Run / dijkstra builds adjacency lists in edge order, then runs the loop above with the
library priority queue; PathTo / path_to walks prev. The listings are the exact files the tests
run. Each language reads one shared fixture (distances, settle order, stale skips and path, including
unreachable nodes, zero weights, a non-zero source and ties), and compares its distances with a
Bellman-Ford reference on 500 random graphs. Bellman-Ford is slower but has no greedy step to get
wrong, which makes it a good independent check.
The lab's own heap is a hand-written binary heap so that you can see its array; the library heaps
lay entries out differently internally, but since entries are unique (distance, node) pairs, every
correct min-heap pops them in the same order.
Language notes
| Language | Heap | Notes |
|---|---|---|
| C# | PriorityQueue<TElement, TPriority> (.NET 6+) |
A min-heap. The priority here is a (int Dist, int Node) tuple, which compares by distance, then node. No decrease-key, hence lazy deletion; TryDequeue returns the element and its priority together. |
| Python | heapq on a list |
Functions over a plain list, always a min-heap. Tuples (distance, node) compare element by element. math.inf is a convenient ∞ because inf + w stays inf. |
| Java | java.util.PriorityQueue |
A min-heap ordered by the comparator you pass (comparingInt(dist).thenComparingInt(node)). remove(Object) exists but is O(n), so lazy deletion is the usual choice. |
| C++ | std::priority_queue |
A max-heap by default; std::greater<> turns it into a min-heap. top() and pop() are separate calls. |
C#, Java and C++ use int.MaxValue / Integer.MAX_VALUE / numeric_limits<int>::max() as ∞. The
code only adds a weight to the distance of a popped (finite) node, so the sentinel itself is never
incremented, but long paths with large weights can still overflow int: switch to 64-bit distances
when weights or path lengths can be big.
Common mistakes
- Using a max-heap. In C++,
std::priority_queue<pair<int, int>>pops the largest distance. - Declaring a node final when it is first reached rather than when it is popped.
- Forgetting the stale check. Without
if d > dist[u]: continue, a stale entry re-expands its node with an outdated distance. The answers stay correct here, but the work can grow far beyond O(E log V). - Running it with negative weights, or "fixing" them by adding a constant to every edge. That penalises paths with more edges and changes which path is shortest.
- Comparing with ≤ in relaxation, which keeps pushing entries for equal distances and makes the predecessor depend on scan order in a less predictable way.
Edge cases
- Source equals target: distance 0, path of one node.
- Unreachable nodes keep ∞ and no predecessor; they are never pushed.
- Zero-weight edges are fine: they settle a node at the same distance as its predecessor.
- Parallel edges: the cheaper one wins at relaxation; the lab accepts one edge per pair only so it can draw them clearly, but the implementations accept multigraphs.
- Self-loops can never improve a distance; the lab rejects them, the implementations tolerate them.
Worked practice
1. In the Six nodes preset, which entries go stale, and why?
Answer
(4, 1), because node 1 is later reached at 3 through node 2; (9, 3), because node 3 drops to 8
through node 1; and (14, 5), because node 5 drops to 12 through node 4. Three stale skips, which is
what the fixture records.
2. A graph has 100,000 nodes and 300,000 edges. Roughly how many heap operations does the lazy version perform at most?
Answer
At most E + 1 = 300,001 pushes (the source plus one per successful relaxation) and the same number of pops, each costing O(log) of the heap size: log₂ 300,000 ≈ 18 levels. Even in an undirected graph an edge succeeds at most once: when its second endpoint is settled, the first endpoint is already settled with a distance that cannot improve.
3. Why can you not stop the first time the target gets a finite distance?
Answer
Being reached only gives an upper bound. A cheaper path through nodes that are still in the heap can lower it later. The distance is guaranteed final only when the target's entry is popped.
4. Every edge in a graph has weight 1. What does Dijkstra do, and what would you use instead?
Answer
It settles nodes in order of hop count, exactly like breadth-first search, but pays O(log V) per heap operation. Plain BFS with a FIFO queue gives the same distances in O(V + E). With weights of only 0 and 1, a deque-based "0-1 BFS" does the same.
Summary
- Dijkstra solves single-source shortest paths when every weight is ≥ 0.
- It relaxes edges out of the closest unsettled node, taken from a min-heap; a popped distance is final.
- Lazy deletion replaces decrease-key: push a new entry, skip stale ones when they pop.
- Binary heap: O((V + E) log V) time, O(V + E) space; an O(V²) array scan wins on dense graphs.
prev[]forms a shortest-path tree; walk it backwards from the target and reverse.- Negative weights break the proof: use Bellman-Ford instead.