Lesson 36 +35 XP

Shortest Paths: Dijkstra's Algorithm

1. Weighted Graphs and the Problem

A weighted graph assigns a weight w(u, v) (distance, time, cost) to each edge. The length of a path is the sum of its edge weights. The single-source shortest-path problem: given a source s, find the shortest path length d(s, v) to every vertex v.

SituationAlgorithmTime
unweighted graphBFS (Lesson 38)O(V + E)
non-negative weightsDijkstraO(V²) or O((V + E) log V)
negative weights allowed (no negative cycle)Bellman-FordO(VE)
all pairsFloyd-WarshallO(V³)

2. Dijkstra's Algorithm

Idea (greedy). Keep a set S of vertices whose shortest distance is final. Repeatedly pick the vertex u ∉ S with the smallest tentative distance, add it to S, and relax every edge (u, v):

if L(u) + w(u, v) < L(v) then L(v) = L(u) + w(u, v)

TEXT
Dijkstra(G, w, s):
  for each vertex v: L(v) = ∞, prev(v) = NIL
  L(s) = 0;  S = φ
  while S ≠ V:
      u = vertex not in S with minimum L(u)
      S = S ∪ {u}
      for each neighbour v of u not in S:
          if L(u) + w(u, v) < L(v):
              L(v) = L(u) + w(u, v);  prev(v) = u

Dijkstra on a 4-vertex graph: shortest path A → C → B → D of length 8 (figure from the Data Structures course)Dijkstra on a 4-vertex graph: shortest path A → C → B → D of length 8 (figure from the Data Structures course)

3. Worked Example

Edges: A-B 4, A-C 2, C-B 1, B-D 5, C-D 8. Source A.

StepVertex added to SL(A)L(B)L(C)L(D)
init-0∞∞∞
1A042∞
2C (L = 2)03 (2 + 1)210 (2 + 8)
3B (L = 3)0328 (3 + 5)
4D (L = 8)0328

Shortest path to D: follow prev pointers D ← B ← C ← A, i.e. A → C → B → D, length 2 + 1 + 5 = 8.

The prev pointers form a shortest-path tree rooted at the source.

4. Why Dijkstra is Correct

** When u is added to S, L(u) = d(s, u).

  • Suppose u is the first vertex added with L(u) &gt; d(s, u).

Take a true shortest path from s to u, and let y be the first vertex on it outside S, with predecessor x ∈ S. x's distance was final and the edge (x, y) was relaxed, so L(y) = d(s, y) ≤ d(s, u) &lt; L(u) (weights are non-negative, so the rest of the path cannot be negative).

But then Dijkstra would have chosen y before u-contradiction.

⚠️ Warning

With a negative edge the argument fails: a later vertex might offer a shortcut to an already-finalised vertex. Use Bellman-Ford instead.

5. Complexity

ImplementationSelect minRelaxTotal
array / adjacency matrixO(V) each, V timesO(1) eachO(V²) - best for dense graphs
binary heap + adjacency listO(log V)O(log V) decrease-keyO((V + E) log V)
Fibonacci heapO(log V) amortisedO(1) amortisedO(E + V log V)
🎯 END-TERM EXAM PREP

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

  • Q1. Explain Dijkstra's algorithm and trace it on a given weighted graph, showing the distance table after each step. (10 Marks)
  • Q2. Why does Dijkstra's algorithm fail with negative edge weights? (2.5 Marks)
  • Q3. Give the time complexity of Dijkstra's algorithm with an array and with a binary heap. (2.5 Marks)