BIT152 ยท 2079 ยท 5 marks
Write the Dijkstra's algorithm to find the shortest path between two nodes in graph.
Write the Dijkstra's algorithm to find the shortest path between two nodes in graph. [5]
Discrete StructureChapter 9: Trees and Graph AlgorithmsDijkstra's algorithm for shortest paths
Quick answer
Dijkstra's algorithm is a greedy algorithm that finds the shortest path from a source node to all other nodes (or a specific destination node) in a weighted graph with non-negative edge weights.
Dijkstra's Algorithm for Shortest Path
Definition
Algorithm Steps
DIJKSTRA(Graph G, source s):
1. Initialize:
- dist[s] = 0 (distance to source is 0)
- dist[v] = โ (distance to all other vertices is infinity)
- prev[v] = NULL (previous node in optimal path)
- Q = set of all vertices (unvisited set / priority queue)
2. While Q is not empty:
a. u = vertex in Q with minimum dist[u] (extract-min)
b. Remove u from Q
c. For each neighbor v of u (still in Q):
- alt = dist[u] + weight(u, v)
- If alt < dist[v]:
dist[v] = alt (relaxation step)
prev[v] = u
3. Return dist[], prev[]
Pseudocode (Formal)
function Dijkstra(G, s):
for each vertex v in G:
dist[v] โ โ
prev[v] โ UNDEFINED
dist[s] โ 0
Q โ all vertices of G
while Q โ โ
:
u โ vertex in Q with min dist[u]
remove u from Q
for each neighbor v of u:
if v โ Q:
alt โ dist[u] + w(u, v)
if alt < dist[v]:
dist[v] โ alt
prev[v] โ u
return dist[], prev[]
Worked Example
Consider the graph:
A --4-- B
| |
2 1
| |
C --3-- D
\ /
5 2
\ /
E
Find shortest path from A to E.
| Step | Visited | dist[A] | dist[B] | dist[C] | dist[D] | dist[E] |
|---|---|---|---|---|---|---|
| Init | - | 0 | โ | โ | โ | โ |
| 1 | A | 0 | 4 | 2 | โ | โ |
| 2 | C | 0 | 4 | 2 | 5 | 7 |
| 3 | B | 0 | 4 | 2 | 5 | 7 |
| 4 | D | 0 | 4 | 2 | 5 | 7 |
| 5 | E | 0 | 4 | 2 | 5 | 7 |
Shortest path: A โ C โ D โ E with cost = 7
Key Properties
| Property | Detail |
|---|---|
| Time Complexity | O(Vยฒ) with array; O((V+E) log V) with min-heap |
| Space Complexity | O(V) |
| Condition | Edge weights must be non-negative |
| Type | Greedy algorithm |
Important Notes
- The relaxation step (
if alt < dist[v]) is the core operation - Dijkstra's algorithm fails with negative weight edges (use Bellman-Ford instead)
- It produces a shortest path tree rooted at the source node
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.