Dijkstra’s Algorithm Explained: Worked Example, Complexity and Exam Traps

Build Dijkstra’s algorithm from its core invariant, trace every relaxation on a six-vertex graph, and learn exactly where the method works and fails.

KnowledgeGate Team

Exam prep & CS education

Updated 5 Dec 20265 min read
Dijkstra’s Algorithm Explained: Worked Example, Complexity and Exam Traps

Most aspirants remember one line about Dijkstra’s algorithm: pick the nearest vertex. The trouble begins when a later relaxation reveals a shorter route and the distance table starts changing. Dijkstra’s algorithm relies on a greedy invariant, a weighted-graph trace, and careful handling of failure cases and exam traps.

What Dijkstra’s algorithm solves

Dijkstra’s algorithm takes a directed or undirected graph G=(V,E)G=(V,E), source SS, and weights w(u,v)≥0w(u,v) \ge 0. It finds the shortest distance from SS to every reachable vertex.

For each vertex vv, it maintains:

  • d[v], the best distance from SS found so far

  • parent[v], the predecessor that produced that distance

  • a settled or unsettled status

Relaxing an edge (u,v)(u,v) means applying d[v] = min(d[v], d[u] + w(u,v)). If the candidate is strictly smaller, both d[v] and parent[v] change.

The final parents form a tree that reconstructs each path. Unreachable vertices remain at infinity. Zero-weight edges are valid, but negative-weight edges are not.

BFS handles unweighted or unit-weight shortest paths; Dijkstra handles non-negative weights. That boundary determines which traversal belongs in a shortest-path solution.

Why the greedy choice is safe

The key invariant is simple: when the unsettled vertex with the smallest tentative distance is extracted, that distance is final.

Suppose a shorter path to the extracted vertex uu exists. Let xx be the first unsettled vertex on that path, with settled predecessor yy. When yy was settled, the edge to xx was relaxed. Since the remaining edges are non-negative, d[x] cannot exceed the claimed shorter path length to uu. Then xx, not uu, should be the minimum, a contradiction.

This is the safe local choice behind Dijkstra’s method. The same habit of proving why a local choice cannot damage the global answer appears in Greedy Algorithms: Strategy and Problems.

Worked example: trace every relaxation from S

Use this directed graph:

S->A (4), S->B (2), B->A (1), A->C (5), B->C (8), B->D (10), A->D (9), C->D (2), C->E (6), D->E (3).

Start with d[S]=0. Every other distance is infinity, and every parent is null. At each step, settle the smallest tentative vertex and relax only its outgoing edges.

Step

Vertex settled

d[A]

d[B]

d[C]

d[D]

d[E]

Parent changes

Initialise

none

infinity

infinity

infinity

infinity

infinity

none

Relax from S

S at 0

4

2

infinity

infinity

infinity

parent[A]=S, parent[B]=S

Relax from B

B at 2

3

2

10

12

infinity

parent[A]=B, parent[C]=B, parent[D]=B

Relax from A

A at 3

3

2

8

12

infinity

parent[C]=A; candidate 3+9=12 ties D, so retain its existing parent

Relax from C

C at 8

3

2

8

10

14

parent[D]=C, parent[E]=C

Relax from D

D at 10

3

2

8

10

13

parent[E]=D

Finish

E at 13

3

2

8

10

13

none

The changes come from direct arithmetic. Through B, A improves from 4 to 2+1=32+1=3. Through A, C improves from 10 to 3+5=83+5=8. The candidate for D is 3+9=123+9=12, equal to its existing value, so no parent change is required. Through C, D becomes 8+2=108+2=10 and E becomes 8+6=148+6=14. Through D, E finally becomes 10+3=1310+3=13.

The final distances are S=0, B=2, A=3, C=8, D=10, E=13. The final tree edges are S->B, B->A, A->C, C->D, and D->E. Therefore the paths are S->B, S->B->A, S->B->A->C, S->B->A->C->D, and S->B->A->C->D->E. An equal-cost relaxation need not replace a parent unless a tie rule is supplied.

Dijkstra graph and extraction stages ending with S=0, B=2, A=3, C=8, D=10, and E=13.

From the trace to an implementation

With an adjacency list and a min-priority queue, the language-neutral procedure is:

Code
for each vertex v:
    d[v] = infinity
    parent[v] = null
d[S] = 0
push (0, S)

while the queue is not empty:
    (du, u) = pop minimum
    if du != d[u]:
        continue
    for each outgoing edge (u, v, w):
        if d[u] + w < d[v]:
            d[v] = d[u] + w
            parent[v] = u
            push (d[v], v)

Without decrease-key, every improvement pushes a fresh pair, leaving older, larger pairs in the heap. The du != d[u] check skips these stale entries. Discovery is not settlement because a better route may appear before minimum extraction.

An adjacency list with a binary heap takes O((V+E) log V) time and O(V+E) space for the graph and algorithm state. An adjacency matrix with a linear scan for the next minimum takes O(V^2) time. A complexity bound is meaningful only with its representation and minimum-selection method.

Traps, ties and the negative-edge failure

Consider S->A (2), S->B (5), B->A (-10), and A->T (2). Dijkstra settles A at 2 and then T at 4 before reaching B. But the path S->B->A costs 5−10=−55-10=-5, and S->B->A->T costs −5+2=−3-5+2=-3. The negative edge creates a cheaper route to an already settled vertex, so the invariant fails.

Use Bellman-Ford when negative weights may occur. If a reachable negative cycle can affect a vertex, no finite shortest path exists for that vertex.

Directed four-vertex counterexample showing edges S->A=2, S->B=5, B->A=-10, and A->T=2, alongside premature labels A=2, T=4 and true route totals 0, 5, -5, -3.

Keep these distinctions clear:

  • A zero-weight edge is not a negative edge.

  • Disconnected vertices remain at infinity.

  • Parallel edges are relaxed independently.

  • A directed edge cannot be followed backwards.

  • Equal tentative distances may produce different but equally valid predecessor trees.

  • Fixed-width integer code should guard against adding a weight to infinity.

Final shortest distances can be unique even when the extraction order or predecessor tree is not. This occurs when equal tentative distances exist and no tie-breaking rule is specified.

How exams turn Dijkstra into questions

Typical questions ask you to complete a tentative-distance table, choose the next settled vertex, recover the shortest-path tree, recompute after one edge changes, select the correct representation-dependent complexity, or choose among BFS, Dijkstra, Bellman-Ford and Floyd-Warshall. In computer networks, Dijkstra also appears inside link-state routing.

Use this 30-second check:

  1. Scan for any negative edge.

  2. Write infinity for every non-source vertex.

  3. After each extraction, relax only outgoing edges.

  4. Record a parent only on strict improvement unless a tie rule is stated.

  5. Stop early only when the requested destination has just been settled.

For question-by-question practice, work through 12 solved items and answer explanations in Dijkstra's Algorithm MCQs. The six-vertex trace, invariant proof, implementation, and negative-edge counterexample above provide the deeper derivation behind those drills. Use the GATE Test Series for timed work, then place the topic inside the broader preparation path through the GATE course category.

The short version and the next drill

  • Dijkstra requires non-negative edge weights.

  • The minimum tentative vertex becomes final when extracted.

  • Relaxation can improve unsettled neighbours and their parents.

  • A binary-heap implementation takes O((V+E) log V) time.

  • Negative edges require a different algorithm.

Now change only C->D from 2 to 5 in the worked graph. Recompute every distance before reading further.

Pause, then check: A=3, B=2, C=8, D=12, E=14. D can keep the route through B with cost 2+10=122+10=12, while E is best through C with cost 8+6=148+6=14.

Retrace both versions without notes. Then continue through the structured algorithms sequence in GATE Guidance by Sanchit Sir.