Find the shortest path from a start node to all other nodes in a weighted graph using Dijkstra's algorithm with a priority queue.
Dijkstra's algorithm finds the shortest path between nodes in a weighted graph with non-negative edge weights. It uses a priority queue to always expand the node with the smallest tentative distance, guaranteeing the shortest path when weights are positive.
Traversal State
Min-Heap Priority Queue
[ ]
Shortest Distances
[ ]
Algorithm & Pseudocode
| Aspect | Complexity |
|---|---|
| Time | O((V + E) log V) |
| Space | O(V) |
| Greedy Choice | Min Distance |
Implementation
1. Distance Array (line 7): Initialized to INT_MAX (infinity), then start node set to 0. This stores the shortest known distance from source to each node.
2. minDistance() Function (lines 9-16): Performs linear search O(V) through all unvisited nodes to find minimum distance. Returns index of nearest unvisited node. Called V times in the algorithm.
3. Main Loop (lines 18-33): Runs V-1 iterations. Each iteration: (a) selects closest unvisited node u, (b) marks u as visited, (c) checks all neighbors of u for relaxation: if dist[u]+weight < dist[v], update dist[v]. This is the core relaxation step.
4. Edge Relaxation (lines 26-30): Updates neighbor distances if path through current node is shorter. Formula: new_dist = dist[current] + edge_weight. Only updates if this is smaller than previously known distance.
5. Time Complexity O(V²): V iterations of main loop × V searches in minDistance() = O(V²). Suitable for dense graphs where E ≈ V². Without heap optimization, linear search dominates. Consider priority queue (binary heap) for sparse graphs to reduce to O((V+E) log V).