Loading lessons...
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.
| Situation | Algorithm | Time |
|---|---|---|
| unweighted graph | BFS (Lesson 38) | O(V + E) |
| non-negative weights | Dijkstra | O(V²) or O((V + E) log V) |
| negative weights allowed (no negative cycle) | Bellman-Ford | O(VE) |
| all pairs | Floyd-Warshall | O(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):
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) = uDijkstra 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.
| Step | Vertex added to S | L(A) | L(B) | L(C) | L(D) |
|---|---|---|---|---|---|
| init | - | 0 | ∞ | ∞ | ∞ |
| 1 | A | 0 | 4 | 2 | ∞ |
| 2 | C (L = 2) | 0 | 3 (2 + 1) | 2 | 10 (2 + 8) |
| 3 | B (L = 3) | 0 | 3 | 2 | 8 (3 + 5) |
| 4 | D (L = 8) | 0 | 3 | 2 | 8 |
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) > 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) < 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.
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
| Implementation | Select min | Relax | Total |
|---|---|---|---|
| array / adjacency matrix | O(V) each, V times | O(1) each | O(V²) - best for dense graphs |
| binary heap + adjacency list | O(log V) | O(log V) decrease-key | O((V + E) log V) |
| Fibonacci heap | O(log V) amortised | O(1) amortised | O(E + V log V) |
📝 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)