1. Gyanastra
  2. Algorithms
  3. Dijkstra's Algorithm: Full Trace, Correctness and Running Times
  4. The Problem and the Setup
Free lesson, no account needed 4 min read

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 G=(V,E)G=(V,E), a weight function w:E→Rw:E\to\mathbb{R}, and a source vertex s∈Vs\in V.

Output: for every vertex vv, the shortest-path weight δ(s,v)\delta(s,v) = minimum over all paths from ss to vv of the sum of edge weights (and ∞\infty if vv is unreachable).

Notation used throughout:

SymbolMeaning
VVnumber of vertices, ∣V∣\lvert V\rvert
EEnumber of edges, ∣E∣\lvert E\rvert
w(u,v)w(u,v)weight of edge (u,v)(u,v)
d[v]d[v]current estimate of δ(s,v)\delta(s,v) (the "distance array")
π[v]\pi[v]predecessor of vv on the current best path
SSset of vertices already finalised (extracted)
QQpriority queue of unfinalised vertices keyed by d[⋅]d[\cdot]

Invariant we maintain: d[v]≥δ(s,v)d[v]\ge\delta(s,v) always (estimates never undershoot), and d[v]=δ(s,v)d[v]=\delta(s,v) once vv is extracted.

Convention note (state both): Dijkstra is normally written 0-indexed in GATE (vertices 0,…,V−10,\dots,V-1); some textbooks (CLRS) use 1-indexed 1,…,V1,\dots,V. The algorithm is identical; only labels change. GATE questions almost always use 0-indexed or letter labels A,B,…A,B,\dots. Distances are non-negative, so there is no sign convention to worry about here (unlike Bellman-Ford).


Relaxation — the Core Operation

Relaxing edge (u,v)(u,v) means: if going through uu gives a shorter route to vv than we currently know, adopt it.

if d[u]+w(u,v)<d[v] then d[v]←d[u]+w(u,v), π[v]←u\textbf{if } d[u]+w(u,v) < d[v] \textbf{ then } d[v]\leftarrow d[u]+w(u,v),\ \pi[v]\leftarrow u

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 dd, finalises it, and relaxes its outgoing edges. Because all weights are ≥0\ge 0, once a vertex is the minimum it can never be improved later — this is the crux of correctness (§5).

Initialisation: d[s]=0d[s]=0, d[v]=∞d[v]=\infty for all v≠sv\ne s, π[v]=NIL\pi[v]=\text{NIL}, S=∅S=\varnothing, Q=VQ=V.


Pages 1–2 of 2