Shortest Path Algorithms

Find shortest paths in weighted graphs with Dijkstra, Bellman-Ford and Floyd-Warshall, and know which to use for given constraints.

Intermediate · about 7 hours · difficulty 4/5

Learn first: Graph Representation, BFS and DFS, Heaps and Priority Queues

When edges have weights, BFS is no longer enough. Pick the algorithm based on edge weights and whether you need one source or all pairs.

Dijkstra's algorithm

For non-negative weights from a single source. Keep a min-heap of (distance, node). Pop the closest unfinalised node and relax its edges: if dist[u] + w < dist[v], update and push. Skip popped entries whose distance is stale. Complexity O((V + E) log V). Negative edges break it because a finalised node could later be improved.

Bellman-Ford

Relax every edge V - 1 times. Works with negative weights in O(V * E). A further improvement on a V-th pass means a negative cycle is reachable. Its "k iterations" structure also solves Cheapest Flights Within K Stops.

Floyd-Warshall

All-pairs shortest paths in O(V^3) with a triple loop over an intermediate node k. Great when V <= 400 and you need every distance.

Choosing

  • Unweighted: BFS. Weights 0 or 1: 0-1 BFS.
  • Non-negative weights: Dijkstra.
  • Negative weights or a limit on edges used: Bellman-Ford.
  • Small V, all pairs: Floyd-Warshall.
  • DAG: relax in topological order in O(V + E).

Pitfalls

Overflow when adding to an "infinity" of INT_MAX, forgetting to skip stale heap entries, and reconstructing paths (store a parent array).

Key concepts

  • Edge relaxation
  • Dijkstra with a min-heap
  • Bellman-Ford and negative cycles
  • Floyd-Warshall all-pairs
  • Path reconstruction with parents
  • Shortest paths on DAGs
  • Choosing the right algorithm

Mini project

Solve 7 problems: Network Delay Time, Path With Minimum Effort, Cheapest Flights Within K Stops, Swim in Rising Water, Find the City With the Smallest Number of Neighbours, Number of Ways to Arrive at Destination, and CSES Shortest Routes I.

Check yourself

Give a small graph with a negative edge where Dijkstra returns a wrong distance, and explain why.

Free resources