Shortest Paths

Choose between BFS, 0-1 BFS, Dijkstra, Bellman-Ford and Floyd-Warshall based on edge weights and graph size.

Intermediate · about 7 hours · difficulty 4/5

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

Shortest path questions differ only in their edge weights. Pick the algorithm by asking what weights are allowed.

Which algorithm

  • Unweighted: plain BFS, O(V + E).
  • Weights 0 or 1: 0-1 BFS with a deque (push 0-edges to the front).
  • Non-negative weights: Dijkstra with a min-heap, O((V + E) log V). The workhorse.
  • Negative weights: Bellman-Ford, O(V * E). One more relaxation round that still improves means a negative cycle.
  • All pairs, small V (up to ~400): Floyd-Warshall, O(V^3).

Key patterns

  • Dijkstra on a grid where cost is the maximum step (Path With Minimum Effort).
  • Dijkstra with extra state, such as stops used (Cheapest Flights Within K Stops, often solved with Bellman-Ford style rounds).
  • Counting shortest paths (Number of Ways to Arrive at Destination).
  • City with the fewest reachable neighbours within a threshold (Floyd-Warshall).

Classic problems

Network Delay Time, Path With Minimum Effort, Cheapest Flights Within K Stops, Shortest Path in Binary Matrix, Number of Ways to Arrive at Destination, Find the City With the Smallest Number of Neighbors, Swim in Rising Water.

Pitfalls

  • Using Dijkstra with negative edges.
  • Not skipping stale heap entries (if the popped distance is larger than the stored one, continue).
  • Using int for distances that can exceed 2e9.

You are ready to move on when you can write Dijkstra with a priority queue from memory and say which algorithm to use for any weight pattern.

Key concepts

  • BFS for unweighted graphs
  • 0-1 BFS
  • Dijkstra with a min-heap
  • Bellman-Ford and negative cycles
  • Floyd-Warshall
  • Shortest path with extra state

Mini project

Solve these 8 in 7 days, log time and pattern: Shortest Path in Binary Matrix, Network Delay Time, Path With Minimum Effort, Cheapest Flights Within K Stops, Number of Ways to Arrive at Destination, Find the City With the Smallest Number of Neighbors at a Threshold Distance, Swim in Rising Water, Shortest Routes I (CSES).

Check yourself

Why does Dijkstra fail with negative edge weights? Give a three-node example.

Free resources