Dijkstra's Algorithm Resource - aloalgo

Dijkstra's Algorithm

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

  1. Start with distance 0 to source, infinity to all others
  2. Always process the vertex with the smallest known distance
  3. Update distances to neighbors if we find a shorter path
  4. 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.
Was this helpful?
© 2026 aloalgo. All rights reserved.