Dijkstra's algorithm finds the shortest path in a weighted graph with non-negative edge weights. It uses a priority queue (min-heap) to always process the closest unvisited vertex first.
The Idea
Start with distance 0 to source, infinity to all others
Always process the vertex with the smallest known distance
Update distances to neighbors if we find a shorter path
Repeat until all vertices are processed
Implementation
Example Walkthrough
With Path Reconstruction
Track the previous vertex to reconstruct the actual path.
BFS vs Dijkstra
BFS: Shortest path in unweighted graphs (all edges cost 1)
Dijkstra: Shortest path in weighted graphs (non-negative weights)
If all edges have the same weight, BFS is simpler and faster. Use Dijkstra when edges have different costs.
Grid with Weights
Complexity
Time: O((V + E) log V) with a binary heap
Space: O(V) for distances and heap
Limitations
No negative weights: Dijkstra assumes all edge weights are non-negative. For negative weights, use Bellman-Ford.
Single source: Finds shortest paths from one source to all other vertices. For all-pairs shortest paths, use Floyd-Warshall.