Algorithms · Dijkstra's Algorithm: Full Trace, Correctness and Running Times
Full Trace on a Six-Vertex Graph
Take this directed graph (0-indexed), source :
0 -> 1 (4) 0 -> 2 (1)
1 -> 3 (2) 2 -> 3 (3) 2 -> 5 (7)
3 -> 4 (1) 5 -> 4 (5)
Edges and weights:
| Edge | Weight |
|---|---|
| 0→1 | 4 |
| 0→2 | 1 |
| 2→3 | 3 |
| 3→4 | 1 |
| 2→5 | 7 |
| 5→4 | 5 |
| 1→3 | 2 |
Initial state: , , (key = current ).
I will show, after each extraction, the extracted vertex, the relaxations performed (with the arithmetic), and the resulting array and .
Extraction 1 — min key is vertex 0 (). . Relax outgoing edges of 0:
- : → , .
- : → , .
. .
Extraction 2 — min key is vertex 2 (). . Relax outgoing edges of 2:
- : → , .
- : → , .
. .
Extraction 3 — min key is vertex 1 (). (Tie with vertex 3 at 4; either order is valid — I take 1 first.) . Relax outgoing edges of 1:
- : . Is ? No → no change.
. .
Extraction 4 — min key is vertex 3 (). . Relax outgoing edges of 3:
- : → , .
. .
Extraction 5 — min key is vertex 4 (). . Vertex 4 has no outgoing edges. No relaxations.
. .
Extraction 6 — min key is vertex 5 (). . Relax outgoing edges of 5:
- : . Is ? No → no change.
. . Done.
Final distances: , , , , , .
Shortest-path tree (via ): , , , , .
0
├──1
└──2
├──3
│ └──4
└──5
Sanity check of the key path : ✓. The alternative : (worse). The alternative : (worse). So is indeed minimal. ✓
Extraction order: — note it is not sorted by vertex number; it is sorted by final distance (with ties broken arbitrarily). This is the single most common place students lose marks: the order is by -value, not by label.
Priority-Queue Behaviour (what the exam wants you to show)
The table below is the "distance array + PQ after every extraction" summary. Keys are current values; a key of means "still in , not yet reached".
| Step | Extract | after (key:vertex) | ||||||
|---|---|---|---|---|---|---|---|---|
| init | — | 0 | ∞ | ∞ | ∞ | ∞ | ∞ | 0:0, ∞:1, ∞:2, ∞:3, ∞:4, ∞:5 |
| 1 | 0 | 0 | 4 | 1 | ∞ | ∞ | ∞ | 4:1, 1:2, ∞:3, ∞:4, ∞:5 |
| 2 | 2 | 0 | 4 | 1 | 4 | ∞ | 8 | 4:1, 4:3, ∞:4, 8:5 |
| 3 | 1 | 0 | 4 | 1 | 4 | ∞ | 8 | 4:3, ∞:4, 8:5 |
| 4 | 3 | 0 | 4 | 1 | 4 | 5 | 8 | 5:4, 8:5 |
| 5 | 4 | 0 | 4 | 1 | 4 | 5 | 8 | 8:5 |
| 6 | 5 | 0 | 4 | 1 | 4 | 5 | 8 | ∅ |
Decrease-key count: each successful relaxation is one decrease-key. In this trace there were 5 successful relaxations (edges ) and 2 failed ones (, ). This matters for the heap analysis in §7.
Correctness Argument
Claim: when Dijkstra extracts from , .
Proof (exchange / greedy-choice argument). Suppose, for contradiction, that is the first vertex extracted with . Consider a true shortest path from to . Let be the first vertex on that is still in when is extracted (such a exists: is already finalised, and itself is in ). Let be the predecessor of on ; then (already finalised).
- Since was finalised and its edges were relaxed, (using the induction hypothesis ).
- Since lies on a shortest path to , (sub-path optimality, and the remaining part of has non-negative weight).
- Therefore .
But was chosen as the minimum key in , so . Contradiction. Hence .
Where non-negativity is used: in the step , we need the suffix of from to to have weight . If a negative edge sits on that suffix, could exceed , the inequality chain breaks, and the greedy choice is no longer safe. That is precisely the failure in §6.
Why Negative Edges Break It — Worked Counterexample
Take three vertices, source :
| Edge | Weight |
|---|---|
| A→B | 1 |
| A→C | 2 |
| C→B | −2 |
True shortest paths: : path has weight , which beats . So . And .
Run Dijkstra: init .
- Extract A (). Relax: : → . : → . Now , .
- Extract B (). B has no outgoing edges. , .
- Extract C (). Relax : . Is ? Yes — but B is already finalised, so Dijkstra never revisits it. The algorithm reports .
Result: Dijkstra outputs , but the truth is . Wrong by 1. The greedy choice of (key 1) over (key 2) was unsafe because the negative edge could later undercut it — exactly the inequality that failed in §5.
Exam takeaway: Dijkstra requires on every edge. If any edge is negative, use Bellman-Ford () or, for a DAG, the topological-order method (§9), which tolerates negative edges.
Running Times — All Three Implementations
The total work is: extractions + (at most) relaxations, each relaxation possibly a decrease-key. The cost depends on the priority-queue data structure.
| Implementation | Extract-min (×V) | Decrease-key (×E) | Total | When to use |
|---|---|---|---|---|
| Array / linear scan | each → | each → | Dense graphs () | |
| Binary heap | each → | each → | Sparse graphs | |
| Fibonacci heap | amortised → | amortised → | Theoretical best; rarely implemented |
Deriving each:
- Array: scanning the whole array to find the min costs ; done times gives . Relaxation is a direct array write, , total . Sum . Since , this is .
- Binary heap: each of extract-mins is → . Each of decrease-keys is → . Sum .
- Fibonacci heap: extract-min is amortised, decrease-key is amortised. Sum .
Choosing in an exam: if the question says "dense graph" or gives , the array version is optimal and simplest. If it says "sparse" or , the binary heap wins. Fibonacci heap is the asymptotically best general bound but has large constants.
Worked numeric check: , (sparse). Array: . Binary heap: . Heap is far better. Now , (dense): array ; heap . Array wins. This is the standard GATE comparison.
Unweighted Shortest Paths — BFS
When every edge has weight (or the graph is unweighted), Dijkstra degenerates to breadth-first search, and we can drop the priority queue entirely.
Method: use a FIFO queue. Set , all others . Repeatedly dequeue , and for each neighbour with , set and enqueue .
Why it is correct: BFS explores vertices in non-decreasing order of distance from (level by level), which is exactly Dijkstra's extraction order when all weights are equal. The FIFO queue is the priority queue, because keys are inserted in sorted order automatically.
Running time: — each vertex enqueued once, each edge scanned once. This is strictly better than any Dijkstra variant, so always use BFS for unweighted graphs.
Tiny check: on the §3 graph ignoring weights, from 0: level 0 = {0}; level 1 = {1,2}; level 2 = {3,5}; level 3 = {4}. So . (Different from the weighted answer, as expected.)
Shortest Paths in a DAG — Topological Order,
If the graph is a DAG (directed acyclic), we can compute shortest paths in even with negative edges, because there are no cycles for a negative edge to exploit.
Method:
- Topologically sort (Kahn's algorithm or DFS, ).
- Initialise , others .
- Process vertices in topological order; for each , relax all outgoing edges .
Why it works: in topological order, every predecessor of is processed before , so by the time we reach , is already final — no priority queue, no re-extraction needed. Each edge relaxed exactly once.
Running time: for the sort plus for the relaxation .
Negative edges are fine here: the §6 counterexample graph is a DAG (topological order ). Processing in that order: ; relax : , ; process : relax : → ; process . Final — correct, unlike Dijkstra. This is the key contrast to remember.