Command Palette

Search for a command to run...

Module 26

Shortest Paths

Cheapest routes in weighted graphs: Dijkstra with a heap, Bellman-Ford for negative weights and edge limits, Floyd-Warshall for all pairs, and Dijkstra variants.

Advanced 3 lessons 7 problems ~40 min of lessons

When edges have different costs (distances, times, prices), the path with the fewest edges isn't necessarily the cheapest, so plain BFS is no longer enough. Shortest-path algorithms find the cheapest route, and each one fits a different situation.

This module teaches Dijkstra's algorithm with a priority queue (the everyday choice for non-negative weights), Bellman-Ford (negative weights, "at most k edges"), and Floyd-Warshall (all pairs on small graphs). It then shows how changing what "cost" means turns Dijkstra into a tool for bottleneck paths, probabilities and counting shortest routes.

Best after: Breadth-First Search, Heaps and Priority Queues

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Plain Dijkstra: the answer is the largest shortest distance.

  2. Minimax Dijkstra on a grid: a path's cost is its largest step.

  3. Bellman-Ford limited to k + 1 edges, relaxing from a copy each round.

  4. Dijkstra with a max-heap and multiplication.

  5. All-pairs distances with Floyd-Warshall on a small graph.

  6. Bottleneck path on a grid: the time needed is the highest cell on the best route.

  7. Counting shortest paths during Dijkstra.