Skip to main content

Dijkstra's shortest path algorithm

Short answer

Dijkstra repeatedly selects the unvisited vertex with smallest tentative distance, finalizes it, and relaxes neighbors. From source A, distances are A=0, C=2, B=3 via C, D=8 via B, E=10 via D. Works only on non-negative weights.

Discuss Dijkstra's shortest path algorithm with suitable example.

Dijkstra's algorithm finds the shortest paths from one source vertex to all other vertices in a weighted graph with non-negative edge weights. It is greedy: it repeatedly selects the unvisited vertex with the smallest known distance, finalises it, and relaxes (updates) the distances of its neighbours.

Algorithm

DIJKSTRA(G, s)
1. for each vertex v: dist[v] = infinity, prev[v] = none
2. dist[s] = 0;  S = empty set
3. while S does not contain all vertices
4.     u = vertex not in S with minimum dist[u];  add u to S
5.     for each neighbour v of u not in S
6.         if dist[u] + w(u,v) < dist[v]
7.             dist[v] = dist[u] + w(u,v);  prev[v] = u

Time: O(V²) with an array, O(E log V) with a binary heap.

Example

Undirected graph with edges A-B 4, A-C 2, B-C 1, B-D 5, C-D 8, C-E 10, D-E 2. Source = A.

StepVertex selecteddist Adist Bdist Cdist Ddist E
Init-0∞∞∞∞
1A (0)042∞∞
2C (2)03 (via C)21012
3B (3)0328 (via B)12
4D (8)032810 (via D)
5E (10)032810

Shortest paths from A:

  • A to C: 2 (A-C)
  • A to B: 3 (A-C-B)
  • A to D: 8 (A-C-B-D)
  • A to E: 10 (A-C-B-D-E)

Dijkstra fails with negative edge weights (Bellman-Ford is used instead).

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 10 questions →