Lesson 39 +40 XP

Shortest Path Algorithms - Dijkstra & Bellman-Ford

Shortest Path Algorithms - Dijkstra & Bellman-Ford

A navigation app must find the cheapest route between two places, where each road has a length, time or toll. In a weighted graph the length (cost) of a path is the sum of its edge weights, and a shortest path from u to v is a path of minimum cost. This is different from a minimum spanning tree: an MST connects all vertices cheaply, while a shortest-path tree gives the cheapest route from one source to each vertex.

Dijkstra shortest pathDijkstra shortest path

1. Kinds of Shortest-Path Problems

ProblemQuestionAlgorithm
Single-sourceShortest paths from one source s to every vertexDijkstra (no negative weights), Bellman-Ford (negative weights allowed)
Single-pairShortest path from s to one target tRun single-source from s and stop at t
All-pairsShortest paths between every pairFloyd-Warshall (Beyond Syllabus lesson), or Dijkstra from every vertex
UnweightedFewest edgesBFS, O(n + e)

2. Relaxation - the Basic Step

Each algorithm keeps an estimate d[v] (best distance found so far from s; initially ∞, and d[s] = 0) and prev[v] (the vertex before v on that path). Relaxing edge (u, v) with weight w asks: is it cheaper to reach v by going through u?

PSEUDO
Algorithm RELAX(U, V, W)
if D[U] + W(U, V) < D[V] then
    D[V] ← D[U] + W(U, V)       // found a shorter path to V
    PREV[V] ← U

Example: d[u] = 5, d[v] = 12, w(u, v) = 4 → 5 + 4 = 9 &lt; 12, so d[v] becomes 9 and prev[v] = u.

The algorithms differ only in which edges they relax and in what order.

3. Dijkstra's Algorithm

Idea (greedy): keep a set of finished vertices whose shortest distance is final. Repeatedly pick the unfinished vertex with the smallest d, mark it finished, and relax all its outgoing edges. Because all weights are ≥ 0, no later path can be cheaper than the current smallest d, so the choice is safe.

Algorithm DIJKSTRA(G, W, S)
for each vertex V do
    D[V] ← ∞; PREV[V] ← NIL; DONE[V] ← FALSE
D[S] ← 0
repeat n times
    U ← vertex with DONE[U] = FALSE and smallest D[U]
    DONE[U] ← TRUE              // D[U] is now final
    for each edge (U, V) do
        if DONE[V] = FALSE then
            RELAX(U, V, W)

Worked example (directed graph)

FromEdges (to : weight)
s2 : 9, 6 : 14, 7 : 15
23 : 24
35 : 2, t : 19
43 : 6, t : 6
54 : 11, t : 16
63 : 18, 5 : 30, 7 : 5
75 : 20, t : 44

Each row: the vertex picked (finished), the relaxations that improved a distance, and the d values afterwards (blank = already finished).

Pick (d)Improvementss234567t
s (0)2 = 9, 6 = 14, 7 = 1509∞∞∞1415∞
2 (9)3 = 33933∞∞1415∞
6 (14)3 = 32, 5 = 4432∞441415∞
7 (15)5 = 35, t = 5932∞351559
3 (32)5 = 34, t = 5132∞3451
5 (34)4 = 45, t = 50453450
4 (45)none4550
t (50)-50

Final distances: 2 = 9, 6 = 14, 7 = 15, 3 = 32, 5 = 34, 4 = 45, t = 50.

Recovering the path: follow PREV back from t: t ← 5 ← 3 ← 6 ← s, so the shortest path is s → 6 → 3 → 5 → t (14 + 18 + 2 + 16 = 50).

Analysis

ImplementationTime
Adjacency matrix, linear scan for the minimumO(n2)
Adjacency list + binary min-heapO((n + e) log n)

Why Dijkstra fails with negative weights

Edges: S→A 2, S→B 5, B→A −4, A→C 1.

  • Dijkstra finishes A first with d[A] = 2, then C with d[C] = 3, then B with d[B] = 5.
  • But S → B → A costs 5 − 4 = 1, so the true d[A] = 1 and d[C] = 2. A was declared final too early.

With negative weights, use Bellman-Ford.

4. Bellman-Ford Algorithm

Idea: a shortest path uses at most n − 1 edges. Relax every edge, n − 1 times. After pass k, every shortest path that uses at most k edges is correct. One extra pass detects negative cycles.

PSEUDO
Algorithm BELLMAN_FORD(G, W, S)
for each vertex V do D[V] ← ∞
D[S] ← 0
for I ← 1 to n - 1 do
    for each edge (U, V) of G do
        RELAX(U, V, W)
for each edge (U, V) of G do    // n-th pass
    if D[U] + W(U, V) < D[V] then
        return "negative cycle"
return D

Trace on the negative-weight example (edge order: SA, SB, AC, BA):

Passd[S]d[A]d[B]d[C]Changes
start0∞∞∞-
10153A = 2, B = 5, C = 3, then BA gives A = 1
20152AC gives C = 2
30152none - answer is final

Negative cycle: a cycle whose total weight is negative (e.g. X → Y 1, Y → X −3). Going round it again and again makes the cost smaller without limit, so no shortest path exists. Bellman-Ford reports this when an edge can still be relaxed after n − 1 passes.

Complexity: O(n × e) - slower than Dijkstra, but more general.

5. Comparison

BasisBFSDijkstraBellman-FordFloyd-Warshall
ProblemSingle source, unweightedSingle sourceSingle sourceAll pairs
Negative weights-NoYesYes
Detects negative cycles-NoYesYes
StrategyLevel orderGreedyRepeated relaxationDynamic programming
TimeO(n + e)O(n2) or O((n + e) log n)O(n × e)O(n3)

MST vs shortest-path tree

BasisMinimum spanning treeShortest-path tree
MinimisesTotal weight of all tree edgesDistance from the source to each vertex
Depends on a sourceNoYes
GraphUndirectedDirected or undirected

6. Applications

  • Road maps and GPS navigation; flight connections.
  • Network routing protocols (OSPF uses Dijkstra; RIP uses a Bellman-Ford style method).
  • Robot and game path finding; currency arbitrage detection (negative cycles).
💡 Tip

Key points to remember - Relax (u, v): if d[u] + w &lt; d[v], then d[v] = d[u] + w and prev[v] = u. - Dijkstra: pick the unfinished vertex with the smallest d, relax its edges; non-negative weights only; O(n2) or O((n + e) log n). - Bellman-Ford: relax all edges n − 1 times; allows negative weights; one more pass detects negative cycles; O(n × e). - Worked example: shortest s → t = 50 via s → 6 → 3 → 5 → t.

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Explain Dijkstra's algorithm. Find the shortest paths from s in the given graph. (10 Marks)
  • Write: relaxation, DIJKSTRA, the pick/distance table, the PREV path s → 6 → 3 → 5 → t = 50, and the complexity.
  • Q2. Why does Dijkstra's algorithm fail with negative edge weights? How does Bellman-Ford handle them? (7.5 Marks)
  • Write: the S, A, B, C counter-example, BELLMAN_FORD, its pass table, and negative-cycle detection.
  • Q3. Differentiate between a minimum spanning tree and a shortest-path tree. (2.5 Marks)