Shortest Paths in Python
Chapter 54: Shortest Paths
5 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Weighted graphs: when roads have prices
A weighted graph gives every edge a number, its weight (a fare, a distance, a time), and a path's cost is the sum of its weights, so "shortest" now means "cheapest", not "fewest edges".
Dijkstra's algorithm with a heap
Keep a frontier of best-known distances in a heap; again and again take the closest place not yet settled, call its distance final, and see whether its roads give any neighbour a shorter distance.
Why negative edges break Dijkstra; Bellman-Ford in brief
Dijkstra settles a place once and never looks again, which is only safe when no road can make a route cheaper later; Bellman-Ford instead relaxes every edge, V − 1 times over, which works with negative weights and also detects a negative cycle.
Shortest paths on grids, and 0-1 BFS
A grid is a graph, each square a place and each step to a neighbour an edge whose weight is the cost of the square you step onto, so Dijkstra works unchanged; and when every weight is just 0 or 1, a deque can replace the heap: free steps go to the front, steps that cost 1 go to the back.
Every pair at once: Floyd–Warshall
dist[i][j] starts as the direct road, and for each town k in turn, every pair (i, j) checks whether going through k is shorter, dist[i][k] + dist[k][j]; after all k, every entry is the shortest route.