Shortest Paths (Dijkstra, Bellman-Ford, Floyd-Warshall)
Find the cheapest route through a weighted graph: the engine behind maps, network routing and many contest problems.
After this lesson you will be able to
- Explain why BFS is wrong once edges have different costs, and what “relaxing” an edge means.
- Run Dijkstra's algorithm by hand and in code with a priority queue, and recover the actual path.
- Explain why Dijkstra needs non-negative edges and what to use instead (Bellman–Ford) when edges can be negative.
- Detect a negative cycle, and use Floyd–Warshall for all-pairs distances on small graphs.
- Choose the right algorithm from the graph's size, weights and what is being asked.
Before you start. BFS (distances on unweighted graphs) and Heap (heapq). Graphs, for adjacency lists with weights.