Skip to content
Data Structures and Algorithms / Shortest Paths, Spanning Trees, and Weighted Graphs

Overview

Topic 4 traversed graphs with unweighted edges; this topic adds edge weights and asks the two questions that dominate real network optimisation: what is the cheapest path between two points, and what is the cheapest way to connect every point at all? Both questions are answered by a single unifying template — the relax-and-check pattern for shortest paths — specialised three ways: Bellman-Ford (handles negative weights, and detects negative cycles), the DAG special case (linear time, reusing topological sort directly), and Dijkstra's algorithm (fastest, but requires non-negative weights). All-pairs shortest paths extends this to every pair simultaneously via Floyd-Warshall's matrix-DP recurrence and Johnson's reweighting trick. Minimum spanning trees (Kruskal, Prim) solve the connectivity-optimisation twin of the shortest-path problem, built on the cut property and cycle property, and Kruskal's implementation motivates Union-Find, a genuinely new data structure whose amortized analysis (the derivation sub-note) is the sharpest amortized bound in the entire unit.

By the end of this topic you should be able to:

  • state and apply the relax-and-check template, and derive Bellman-Ford's, the DAG algorithm's, and Dijkstra's running times from it;
  • explain why Dijkstra requires non-negative weights and Bellman-Ford does not;
  • derive the Floyd-Warshall recurrence and explain Johnson's reweighting trick;
  • prove the cut property and cycle property, and use them to justify Kruskal and Prim;
  • implement Union-Find with union-by-rank and path compression, and state (and, in the derivation note, prove) its near-constant amortized cost.

In this lesson

  1. Contents
  2. The big picture

The full lesson is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or explore the curriculum.