synopsis · Trees & graphs · chapter 27
Shortest Paths
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
Relax an edge:
if (dist[u] + w < dist[v]) dist[v] = dist[u] + w;. Every algorithm here is relaxation in a different order. - use it when
Weights ≥ 0 → Dijkstra. Negative or "at most k edges" → Bellman–Ford. All pairs, V ≤ ~400 → Floyd–Warshall. Only 0/1 → 0-1 BFS.
- template
Heap of {dist, node}: poll →
if (d > dist[u]) continue;→ relax every edge → push each improved {dist[v], v}. - cost
Dijkstra O((V + E) log V) · Bellman–Ford O(V·E) · Floyd O(V³) · 0-1 BFS O(V + E) · plain BFS O(V + E) when all edges cost the same.
- trap
Dijkstra + a negative edge = wrong answers. "Polled means final" only holds when no edge can shrink a path later.
- trap
(a, b) -> a[0] - b[0]can overflow andInteger.MAX_VALUE + wwraps negative. UseInteger.compare; check ∞ before adding. - trap
Floyd–Warshall: the middle stop
kis the OUTER loop. K-stops Bellman–Ford: clone the array each round. - pro tip
Path cost is a max (effort, water level) or a product ≤ 1? Same Dijkstra — swap
+formaxor×, keep the heap. - pro tip
Target known? Return when it is polled, not when it is first pushed.
Shaky on a card? Open the chapter or flip its recall cards.