Shortest paths, topological sort and union-find
BFS finds shortest paths when every edge costs the same. Real graphs have weights: kilometres, minutes, prices, latencies. This lesson covers the algorithms behind route planners, build systems and network design: Dijkstra's algorithm, topological sorting, union-find and minimum spanning trees.
Dijkstra's algorithm
Find the cheapest path from one node to all others, when edge weights are non-negative. Always expand the closest unfinished node next, using a min-heap:
O((V + E) log V) with a heap. Once a node is popped with its smallest distance, that distance is final, which is exactly why negative weights break Dijkstra: a later negative edge could make an already-finished node cheaper.
- With negative edges (but no negative cycles), use Bellman–Ford: relax every edge V − 1 times, O(V·E). A further pass that still improves something reveals a negative cycle (useful for spotting currency arbitrage).
- For a single destination on a map, A* adds a heuristic (straight-line distance to the goal) to explore promising directions first; it's what games and navigation apps use.
Topological sort
In a directed acyclic graph (DAG) of dependencies, a topological order lists every task after all the tasks it depends on: build steps, course prerequisites, spreadsheet formulas, package installation. Kahn's algorithm repeatedly takes tasks with no remaining prerequisites:
O(V + E). Python's standard library has it too: graphlib.TopologicalSorter.
Union-find (disjoint set union)
Union-find tracks which items belong to the same group, supporting two operations: find (which group is x in?) and union (merge two groups). With path compression and union by size, both are effectively O(1):
It answers connectivity questions as edges arrive (network connections, merging duplicate accounts, image segmentation) and detects cycles in undirected graphs: adding an edge whose ends are already in the same group creates a cycle.
Minimum spanning tree (Kruskal)
Connect all nodes as cheaply as possible (laying cable, building roads): sort edges by cost and add each one unless it would create a cycle, which union-find tells you instantly:
O(E log E), dominated by sorting the edges.
Choosing a graph algorithm
| Question | Algorithm |
|---|---|
| Reachable? Connected components? | BFS or DFS, or union-find |
| Shortest path, all edges equal | BFS |
| Shortest path, non-negative weights | Dijkstra |
| Shortest path with negative weights | Bellman–Ford |
| Shortest path to one goal with a good heuristic | A* |
| All-pairs shortest paths, small graph | Floyd–Warshall, O(V³) |
| Order tasks by dependencies | Topological sort |
| Cheapest way to connect everything | Kruskal or Prim |
| Is there a cycle? | DFS colours (directed), union-find (undirected) |
Practice
- Network delay: given travel times between servers, how long until a signal from server 1 reaches every server (Dijkstra, then the maximum distance)?
- Course schedule: can all courses be finished? Return any valid order, or an empty list.
- Count the connected components of
ncomputers given a list of cable connections, using union-find.
1.Why does Dijkstra's algorithm fail with negative edge weights?
2.What does a topological order guarantee?
3.How does Kruskal's algorithm avoid cycles?