Dijkstra's Algorithm
BFS finds the shortest path when all roads cost the same. But what about a real map where roads have different travel times? You need Dijkstra's algorithm.
Think of it like a GPS. It knows all the road speeds and continuously picks the fastest next road — always choosing the route that gets you there soonest. Dijkstra works on graphs with non-negative edge weights. For negative weights, use Bellman-Ford.
The core idea: always settle the cheapest node next
Keep a distance table — infinity for every node except the start (distance 0). Use a min-heap to always process the node with the lowest known cost. When you process a node, check whether any of its neighbors can be reached more cheaply through it. If yes, relax (update) their distance.
← → arrow keys to step · click elements to interact
Dijkstra's Algorithm
Why the greedy approach works
Because all edge weights are non-negative, once a node is popped from the min-heap with distance d, no shorter path to that node can be discovered later. Any later path must go through nodes with equal or greater distances — only adding more cost. This guarantee makes the algorithm correct.
Reconstructing the path
Keep a prev table: whenever you relax a neighbor through the current node, record prev[neighbor] = current. Walk backward from the destination through prev to reconstruct the full route.
Heap vs plain array
With a min-heap: \(O((V+E)\) log V). With a plain array (scan for minimum each step): \(O(V^2)\). For sparse graphs the heap wins; for very dense graphs the difference narrows.
Complexity
Shortest Path with Route Reconstruction
Quick check
Continue reading