Part 5 · 2 chapters · ~12 min

Graphs

Representations (adjacency lists and matrices), BFS and DFS, connected components and cycle detection, topological sort, Dijkstra and Bellman-Ford (with FX arbitrage detection), minimum spanning trees, maximum flow and bipartite matching, and recognising graph problems in disguise.

10

Algorithms by question

code
// BFS: fewest hops between two accounts in a transfer graph
function hops(adj: Map<string, string[]>, from: string, to: string): number {
  const dist = new Map([[from, 0]]); let q = [from];
  while (q.length) { const next: string[] = [];
    for (const u of q) for (const v of adj.get(u) ?? []) if (!dist.has(v)) { dist.set(v, dist.get(u)! + 1); if (v === to) return dist.get(v)!; next.push(v); }
    q = next; }
  return -1;
}
// Kahn's topological sort: run migrations in dependency order, or report a cycle
function topo(deps: Map<string, string[]>): string[] {
  const indeg = new Map<string, number>(); for (const [n, ds] of deps) { indeg.set(n, indeg.get(n) ?? 0); for (const d of ds) { indeg.set(d, indeg.get(d) ?? 0); } }
  for (const [n, ds] of deps) indeg.set(n, ds.length);
  const order: string[] = [], q = [...indeg].filter(([, k]) => k === 0).map(([n]) => n);
  const users = new Map<string, string[]>(); for (const [n, ds] of deps) for (const d of ds) users.set(d, [...(users.get(d) ?? []), n]);
  while (q.length) { const n = q.shift()!; order.push(n); for (const u of users.get(n) ?? []) { indeg.set(u, indeg.get(u)! - 1); if (indeg.get(u) === 0) q.push(u); } }
  if (order.length !== indeg.size) throw new Error('cycle');
  return order;
}
GRAPH ALGORITHMS, BY QUESTION
pick the algorithm from the question you are asking
graphaccounts and transfersBFSfewest hopsDFSreachability, cyclestopological sortorder with dependenciesDijkstracheapest path (no negative edges)MSTconnect all cheaplymax flowcapacity between two points
swipe the figure sideways, or tap expand for full screen
1/5
BFS
Breadth-first search explores in rings of distance: the shortest path in hops in an unweighted graph ("how many transfers separate these two accounts?"). O(V + E) with a queue.
fewest hops, with a queueO(V + E)
11

Graphs in disguise

problem as statedgraph problem
do these accounts belong to the same fraud ring (shared devices, phones)?connected components (union-find)
in what order should these services deploy?topological sort
is there an FX arbitrage loop (rates multiply to more than 1)?negative cycle with weights −log(rate) (Bellman-Ford)
assign agents to customers, each agent oncebipartite matching (max flow)
word ladder, puzzle states, network hopsBFS over implicit graphs