Algorithms · Dijkstra's Algorithm: Full Trace, Correctness and Running Times
The Problem and the Setup
This chapter takes the single-source shortest-path problem for non-negative edge weights and drills it to exam depth: the relaxation step, a complete six-vertex trace with the distance array and priority queue after every extraction, the correctness proof, a worked counterexample showing exactly why negative edges break it, all three running-time analyses, and the two special cases (BFS for unweighted graphs, topological order for DAGs). Every distance is recomputed from scratch so you can check each arithmetic step.
Input: a directed or undirected graph , a weight function , and a source vertex .
Output: for every vertex , the shortest-path weight = minimum over all paths from to of the sum of edge weights (and if is unreachable).
Notation used throughout:
| Symbol | Meaning |
|---|---|
| number of vertices, | |
| number of edges, | |
| weight of edge | |
| current estimate of (the "distance array") | |
| predecessor of on the current best path | |
| set of vertices already finalised (extracted) | |
| priority queue of unfinalised vertices keyed by |
Invariant we maintain: always (estimates never undershoot), and once is extracted.
Convention note (state both): Dijkstra is normally written 0-indexed in GATE (vertices ); some textbooks (CLRS) use 1-indexed . The algorithm is identical; only labels change. GATE questions almost always use 0-indexed or letter labels . Distances are non-negative, so there is no sign convention to worry about here (unlike Bellman-Ford).
Relaxation — the Core Operation
Relaxing edge means: if going through gives a shorter route to than we currently know, adopt it.
That is the whole engine. Dijkstra's only addition is the order in which it relaxes: it always extracts the unfinalised vertex with the smallest , finalises it, and relaxes its outgoing edges. Because all weights are , once a vertex is the minimum it can never be improved later — this is the crux of correctness (§5).
Initialisation: , for all , , , .