CComputer Science, Built

Act IV · Algorithms

Part 18 of 61

Graphs

Degreestarts at this level45 min of film18 chaptersprerequisites: Part 2, Part 16, Part 17

What can be computed about a map, a network or a web of links once it is drawn as dots and lines?

In 1736 the citizens of Koenigsberg asked whether a walk could cross each of their seven bridges exactly once, and Euler answered by throwing away everything but which land mass each bridge joins: a circuit exists exactly when the graph is connected and every degree is even. From that abstraction the part builds the standard algorithms, each with the proof that makes its output checkable. Breadth-first search finds layers and odd cycles, depth-first search stamps intervals, and from them come topological order and strongly connected components. Dijkstra's algorithm, designed in twenty minutes at a cafe, rests on an invariant about settled vertices that one negative edge breaks; Bellman-Ford, Floyd-Warshall and Johnson's reweighting repair that. On a synthetic city, forty exact routes cost about 2,525 vertex expansions with Dijkstra, 657 with straight-line A* and 113 with a contraction hierarchy. Minimum spanning trees follow from an exchange argument, and a maximum flow is certified by a cut of the same value, 19 on the worked example. Matching, PageRank and planar colouring follow, and the gap between Euler's circuits and Hamilton's cycles is the first sight of P against NP. The last chapter states recent shortest-path and flow results with their models and dates.

What you need. Part 16's O-notation and Part 17's heaps and union-find. Proof by induction and by contradiction, as in Part 2.

Mathematics, ideas and history
BFS/DFS, SCCs, Dijkstra and the 2024–25 results, Bellman–Ford, MSTs, max-flow min-cut, matching and Gale–Shapley, PageRank
What we build or compute
shortest paths on a city grid; flows

What you will be able to do

Degree

  • Decide whether a multigraph has an Euler circuit and construct one with Hierholzer's algorithm.
  • Run BFS, DFS and Dijkstra by hand, and state the invariant that makes Dijkstra's settled distances final.
  • Build a minimum spanning tree with Kruskal's or Prim's algorithm and justify each edge by the cut property.

Graduate

  • Prove the max-flow min-cut theorem from the residual graph, and read a minimum cut off a maximum flow.
  • Prove that Johnson's reweighting keeps shortest paths and makes every weight nonnegative.
  • Prove that Gale-Shapley ends with a stable matching, and that five colours suffice for a planar graph by Kempe chains.

Research

  • State the 2024 universal-optimality result for Dijkstra and the 2025 bound beyond the sorting barrier, each with its model: comparison-addition, real weights, distance-only output.
  • Say what remains open for distance-only single-source shortest paths in O(m + n) time.

Industry

  • Choose between Dijkstra, bidirectional search, A*, landmarks and contraction hierarchies for a routing service, counting preprocessing and per-query work separately.
  • Compute PageRank by power iteration with dangling pages handled, and bound the error from the stationarity residual, not from the last change.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 20 min · Graduate 42 min · Research 45 min · Industry 25 min.

  1. 0Seven bridgesDegree2 min
  2. 1Euler's bridges, and how to store a graphDegree2 min
  3. 2Breadth-first searchDegree2 min
  4. 3Depth-first searchDegree2 min
  5. 4Topological sortDegree2 min
  6. 5Strongly connected componentsGraduate3 min
  7. 6Dijkstra's algorithmDegree3 min
  8. 7Negative edgesDegree2 min
  9. 8All pairsGraduate2 min
  10. 9Exact routes with less searchIndustry3 min
  11. 10Minimum spanning treesDegree2 min
  12. 11Flows and cutsGraduate3 min
  13. 12MatchingGraduate2 min
  14. 13Easy and hardGraduate2 min
  15. 14PageRankIndustry2 min
  16. 15Planar graphs and four coloursGraduate3 min
  17. 16Research results: models and datesResearch3 min
  18. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

Seven bridgesDegree2 min

In 1736 the city of Königsberg had seven bridges joining two river banks and two islands. Its citizens asked whether one could walk through the city crossing every bridge exactly once. Leonhard Euler answered by throwing almost everything away. The shape of the land, the lengths of the bridges, the streets: none of it matters. Only which land masses each bridge connects. Four dots, seven lines. Euler had invented the graph, and in one paper proved the walk impossible.

Euler's abstraction turned out to describe almost everything. A road map is a graph of intersections and roads; the internet, of routers and links; a compiler's program, of instructions and the flow of control between them. A build is a graph of files and dependencies, the web of pages and links, a currency market of currencies and exchange rates. And the questions are the same few: how to get from here to there, in what order, how cheaply, how much can flow, which things belong together. This part answers each one, with proofs.

Here is where we are going. Breadth-first and depth-first exploration, and the different structure each reveals. Dijkstra's shortest-path invariant, then exact route searches that expand fewer intersections after preprocessing. Spanning trees, flows and cuts, with a proof that maximum flow equals minimum cut. Stable matching, PageRank, and the difference between visiting every edge and visiting every vertex. Finally, two distinct research tasks: sorting vertices by distance, and computing distances without sorting them. Their bounds need not be the same.

1Euler's bridges, and how to store a graphDegree2 min

Euler's argument counts entrances and exits. Passing through a vertex uses two incident edges, one arriving and one leaving. A closed trail using every edge once therefore requires even degree everywhere; a loop contributes two to degree. An open trail with different endpoints instead has exactly two odd vertices. In either case all vertices incident to edges must lie in one connected component. Königsberg has degrees five, three, three and three: four odd vertices, so neither kind of trail can cross every bridge once. For a connected graph, the even-degree condition is also sufficient. Hierholzer's construction, published in 1873, gives the circuit explicitly.

The proof becomes a stack algorithm. Start at a vertex with an edge and follow unused edges. At a vertex other than the start, entering consumes one of an even number, so an unused exit remains whenever the walk would otherwise stop. The walk closes at its start. If edges remain, connectivity gives a detour from a vertex already on the circuit; splice that closed detour into it. Our implementation pairs edge incidences with identifiers and skips used identifiers. It handles each incidence a constant number of times, including validation: expected order V plus E with hash tables, rather than repeatedly removing from the middle of a list. The highlighted edges show the checked circuit on this graph.

Storage models and measured programs are different things. Adjacency lists need order V plus E entries. The first table estimates eight-byte neighbour entries and row references; it excludes Python object overhead. An ideal packed matrix uses one bit per ordered vertex pair. Our measured NumPy boolean matrix instead uses one byte per cell; its actual data allocation is shown separately. The timing table scans the complete graph three times and reports the minimum: Python visits every list entry, while NumPy counts each complete boolean row. Both must count exactly twice the undirected edges. The dense case favours this vectorized matrix scan on this host.

2Breadth-first searchDegree2 min

Breadth-first search explores a graph the way a flood fills a maze. Start at one vertex. Visit all its neighbours, then all of their unvisited neighbours, layer by layer, using a first-in, first-out queue so that nearer vertices are always handled first. The colour here is the layer: the number of steps from the entrance. When the flood reaches the exit, following the recorded parents back gives a path, and it is a shortest one. Edward Moore described exactly this in 1959, for finding the shortest path through a maze.

Why is the first discovered path shortest in edge count? The FIFO queue releases vertices in nondecreasing layer order. At any moment it contains the remaining vertices of layer k followed by some of layer k plus one. A vertex first discovered from layer k gets a path of k plus one edges. Any shorter path would have reached it from an earlier layer, which was already processed: a contradiction. Each reached vertex enters the queue once. Each directed adjacency entry is scanned once; an undirected edge has two such entries. Including initialization, the bound is order V plus E. These are unweighted distances. The same traversal pattern appears in social-network separation and Part 15's copying collector.

Breadth-first layers also test an undirected graph for bipartiteness. Start a search in each component and alternate colours by layer. If every edge crosses between colours, the two colour classes form a bipartition. Otherwise an edge joins equal-depth vertices. Follow their parent paths only as far as their lowest common ancestor, then add this edge: that is a simple odd cycle, which cannot be two-coloured. The maze uses only horizontal and vertical grid edges, so coordinate parity gives a bipartition. The test helps recognize two-sided matching instances; a scheduling application also needs its conflicts to have exactly this graph interpretation.

3Depth-first searchDegree2 min

Depth-first search is the other way to explore. Follow an unexplored edge, and from there another, as far as possible; when every edge out of the current vertex has been tried, back up one step and continue. It uses a stack, or plain recursion, where breadth-first search used a queue. It is the thread Theseus unwound in the labyrinth, and Charles Trémaux wrote it down for mazes in 1882. The useful trick is to stamp each vertex twice with a clock: once when it is first discovered, once when it is finished. John Hopcroft and Robert Tarjan showed in the early 1970s how much structure those two numbers reveal, and won the Turing award for it.

Draw each vertex's lifetime from discovery to finish. Two DFS intervals are either disjoint or one contains the other: never a partial overlap. The search finishes a vertex only after completing its recursive descendants. Proper interval containment is exactly strict ancestry in the DFS forest. The white-path theorem makes this precise: v becomes a descendant of u exactly when, just as u is discovered, a path from u to v has every vertex after u still undiscovered. The source u itself has just changed colour; the theorem does not require it to remain white.

The stamps also sort every edge into one of four kinds. Tree edges are the ones the search followed to discover a new vertex. Back edges lead to an ancestor that is still open, and each one closes a cycle. Forward edges jump to a descendant already finished, and cross edges go sideways, to a finished vertex in another branch. The most useful consequence: a directed graph contains a cycle exactly when the search finds a back edge. Everything happens in linear time, and the next two chapters are built on these stamps.

4Topological sortDegree2 min

Here is the build of a small compiler. Each arrow says that one file must be made before another: the header before every object file that includes it, the object files before the linked compiler, the compiler before the tests. A topological order is a list in which every file comes after all of its prerequisites; it exists exactly when there are no cycles. Depth-first search finds one for free. Sort the vertices by finishing time, latest first. Along any edge, the search finishes the target before the source, because the target is either explored from the source or already done; a back edge would be a cycle.

Arthur Kahn's method from 1962 is the one build tools usually use. Count the incoming edges of every vertex. Any vertex with none can be built now: output it and remove its outgoing edges, which may free others. The vertices that become free at the same moment do not depend on each other, so they can be built in parallel. If at some point vertices remain but none is free, the remaining ones contain a cycle, and the build is impossible: make reports a circular dependency.

Topological order applies when dependencies form a directed acyclic graph. It orders compilation prerequisites and acyclic spreadsheet recalculation. In a DFS forest, decreasing finish time orders the graph after its back edges are removed; a control-flow graph itself may still have loops. Package managers may need extra policy for cycles, versions and optional dependencies. A longest path in a DAG is also computed in one topological pass. With task durations as weights, unlimited workers and no other resource or communication costs, the critical-path length is the minimum project completion time.

5Strongly connected componentsGraduate3 min

In a directed graph, reaching is not symmetric: a one-way street can take you somewhere you cannot come back from. Two vertices belong to the same strongly connected component if each can reach the other. Here the graph splits into three. Shrink each component to a single point and the result, the condensation, has no cycles at all: any cycle between components would merge them. So every directed graph is a DAG of strongly connected pieces.

Tarjan's algorithm finds components in one depth-first search. Assign discovery indices and keep vertices of unfinished components on an active stack. Initialize low of v to its own index. After a DFS child finishes, include that child's low value; for an edge to an already discovered vertex still on the active stack, include that vertex's discovery index. These are different update rules. When low of v equals its index, pop the active stack through v: those vertices form one component. Components emerge in reverse topological order of the condensation. Kosaraju's alternative uses decreasing finish times, followed by searches on the reversed graph. Both methods take order V plus E with adjacency lists.

Components reveal network structure, but a generator is not a web measurement. This synthetic graph has twenty thousand pages. New pages prefer popular older ones, and some links are returned. Its checked table has a large core, an incoming region, and zero pages in the outgoing-only region. The separate bow-tie diagram describes Broder and colleagues' May 1999 crawl, reported in 2000: about twenty-eight percent core, twenty-one percent incoming and twenty-one percent outgoing, with other regions outside them. Those are historical observations on a different graph. Linear-time SCC algorithms explain why such decomposition is possible; this episode neither reproduces that crawl nor measures today's web.

Strong components solve two-SAT. Each clause here is a disjunction of two literals. A or B yields the implications not A to B and not B to A. Put every literal and its negation in the implication graph. The formula is unsatisfiable exactly when a variable shares a strong component with its negation. Otherwise, choose a topological order of the condensation and set x true precisely when x's component is later than the component of not x. Comparing these two components is essential. Our checked example sets x one and x three true and x two false. With three literals per clause, general satisfiability is NP-complete; Part 26 explains the distinction.

6Dijkstra's algorithmDegree3 min

Edsger Dijkstra designed his shortest-path algorithm in about twenty minutes, sitting at a café in Amsterdam in 1956, to demonstrate a new computer. Every vertex gets a tentative distance: zero for the start, infinity for the rest. Repeatedly take the unsettled vertex with the smallest tentative distance, declare it settled, and relax its outgoing edges, lowering a neighbour's distance whenever the path through this vertex is shorter. Watch the order: s, then b at distance one, then a at three, reached more cheaply through b than directly. A priority queue, Part 17's heap, finds the nearest vertex, so the whole run costs order of V plus E, times log V.

The proof is an invariant, as in Part 16. Claim: whenever a vertex is settled, its tentative distance is its true shortest distance. Suppose not, and let u be the first vertex settled too early: some path P to u is shorter than its tentative distance. P starts inside the settled set and must leave it somewhere; let y be the first vertex on P that is not yet settled. Its predecessor on P was settled correctly and relaxed the edge into y, so d of y is at most the length of P up to y, which is at most the length of P, which is less than d of u. But the algorithm chose u because d of u was smallest, so d of u is at most d of y. That is a contradiction, and the step that the length of a path only grows as it continues is exactly where edge lengths must be non-negative. Chapter seven shows what breaks without it.

Here is Dijkstra on a synthetic city of two thousand four hundred intersections. A dot appears when an intersection is settled, coloured by its distance from the source. Gold arterial edges cost zero point three five times their geometric length, so the wavefront advances farther along them; these are synthetic travel costs. A point-to-point query settles vertices in distance order until the destination is selected. How much of the city that includes depends on the destination. Chapter nine compares exact alternatives on fixed queries.

7Negative edgesDegree2 min

Dijkstra's proof needed every edge to be non-negative. Here, the algorithm settles a at distance two, because that is the smallest tentative distance, and moves on. But going through b costs five, minus four: one. The path that looked worse became better after its last step. The step of the proof that said a path only grows as it continues is simply false here. And negative weights are not exotic: they model rebates and gains, they appear when costs are measured against a reference, and in the next minute they will model exchange rates.

Bellman-Ford permits negative edges. Repeatedly relax every directed edge. After round k, distances are at least as good as every source path using at most k edges. With in-place updates, a round may propagate farther; the table shows this distinction. If no reachable negative cycle exists, a shortest path can be simple and uses at most V minus one edges. That many rounds suffice, giving order V times E. An improvement in one more round detects a negative cycle reachable from the source. Only vertices downstream of such a cycle have distances unbounded below; unrelated finite distances need not disappear. Distributed distance-vector routing uses related relaxations, with separate convergence and failure-handling issues.

A rate product gives a negative-cycle example. These four-currency rates are invented illustrations, not market observations. Multiplying rates around a loop gives the gross conversion factor, before fees, spreads and execution constraints. Weight each edge by minus the logarithm of its rate. A product greater than one becomes a negative cycle because logarithms turn products into sums. The checked example finds yen to pounds to euros and back to yen. Its gross gain is about half a percent. The implementation uses floating arithmetic and a small relaxation tolerance, so a nearly zero cycle needs numerical care.

8All pairsGraduate2 min

Sometimes we need all pairwise distances. Floyd-Warshall uses three nested loops over intermediate vertex k, source i and target j. Before step k, d k of i, j is the shortest path allowing only vertices numbered below k as internal waypoints. Initialize the diagonal to zero and other entries to edge weights or infinity. When k becomes allowed, a shortest path either avoids k or splits there into an i-to-k part and a k-to-j part. This recurrence gives cubic time and quadratic space. Negative edges are allowed, but a reachable negative cycle can make some pairwise distances unbounded; a negative final diagonal detects that obstruction.

For a sparse graph without negative cycles, Johnson reweights before running Dijkstra. Repeated binary-heap searches can exploit sparsity, while the initial Bellman-Ford computation still has its own cost. Add a genuinely fresh source, joined to every vertex by zero-weight edges, and compute its distances p. A negative cycle aborts this construction. Reweight u-to-v by w plus p of u minus p of v. The shortest-path triangle inequality makes every reweighted edge nonnegative. Along a path, potentials telescope: every path with the same endpoints changes by the same constant, preserving its shortest choices. Our potential-generated test graph keeps its original negative edges. Every finite distance and every unreachable pair agrees with Floyd-Warshall; no fallback changes the input.

All-pairs distances also have an algebraic form. Define the i-j entry of a product as the minimum over k of a i-k plus b k-j. This is the min-plus product. With a zero diagonal, the k-th min-plus power describes walks of at most k edges. Without negative cycles, V minus one edges suffice for shortest paths, so repeated squaring reaches the answer. Fast ordinary matrix multiplication does not automatically transfer: subtraction is not available in min-plus arithmetic. The general weighted APSP conjecture rules out a fixed polynomial improvement below cubic time in its stated model. Restricted weight ranges and graph classes have different algorithms and are not ruled out by this broad slogan.

9Exact routes with less searchIndustry3 min

A point-to-point search can use its destination. The left panel shows intersections actually expanded by Dijkstra on this query, not every vertex merely discovered. White is the source and red the target. A star prioritizes distance so far plus a lower bound on the remaining distance. With nonnegative edges, an admissible estimate, zero at the goal, and reopening when an improved path reaches a previously expanded vertex, the answer is exact. Our straight-line bound uses the cheapest cost per unit distance, zero point three five. It is also consistent on every city edge, so this experiment needs no reopening. The right panel shows its actual expansions.

Road structure can give a stronger estimate than a straight line. Precompute distances to and from four landmarks once, and reuse those tables across queries. On this undirected city the two directions agree. The triangle inequality bounds distance from v to the target below by distance from a landmark to the target minus distance from that landmark to v; the reverse-direction difference gives another bound. Take the largest valid bound over landmarks. The two panels show actual expansions for the same diagonal query, with both final distances checked equal. Tables cost order landmarks times vertices in storage. Preprocessing cost and expanded-vertex count are different measurements; neither is a query-latency benchmark.

Contraction hierarchies precompute shortcut edges. Choose a vertex order; our implementation uses a heuristic based on added shortcuts and contracted neighbours, not a supplied road-importance label. When contracting v, preserve a path between each pair of remaining neighbours. If no equally short witness avoiding v is found, add a shortcut. Here length one plus two becomes a shortcut of three, while the alternative costs seven. The query searches upward in the order from both endpoints. The dots show those two expansion sets on the same diagonal trip. Shortcuts ensure that some shortest route has an equivalent upward-then-downward representation; not every original shortest path literally has that shape. A bounded witness search can add extra shortcuts without losing correctness. Performance depends on the graph, ordering and implementation.

These are forty fixed queries on one synthetic city of four thousand eight hundred intersections. The bars count actual expanded vertices, averaged over queries. Bidirectional searches count both sides; they may count an intersection twice. We independently check every reported route distance against the plain Dijkstra result. Landmark tables are reused, and hierarchy preprocessing is recorded separately as one observed build. Fewer expansions explain a possible source of savings, but do not measure response time. This experiment makes no claim about phone latency or how the ratio scales to a continental network.

10Minimum spanning treesDegree2 min

A minimum spanning tree connects a connected undirected weighted graph with the least total edge weight. It has V minus one edges and no cycle. The weights may be negative; shortest-path assumptions are not needed here. For any cut, any lightest crossing edge belongs to some minimum spanning tree. Add that edge to a minimum tree that avoids it. The resulting cycle crosses the cut again; replace a crossing edge of at least its weight. The new tree is no worse and contains the chosen edge. The related cycle rule needs care with ties: an edge uniquely heaviest on a cycle belongs to no minimum tree. A tied maximum edge may belong to one. The three classic algorithms use these safe choices in different orders.

Joseph Kruskal's algorithm is the cut property applied greedily. Sort all the edges by weight, and go through them from the lightest, keeping each edge unless it would close a cycle. Whether two points are already connected is exactly the question Part 17's union–find answers in almost constant time. Watch the forest form: short edges first, joining nearby points into clusters, then longer edges joining clusters. The result, on these hundred and twenty points, has the same total length that Prim's and Borůvka's algorithms find.

Three classic methods schedule safe edges differently. Kruskal sorts edges and uses union-find, taking order E log E for this implementation. Prim grows one tree using a heap; Jarník described an earlier version. The binary-heap bound differs from a Fibonacci-heap implementation. Boruvka lets each remaining component choose a lightest outgoing edge, with a consistent tie rule. On a connected graph the number of components at least halves per round. Karger, Klein and Tarjan's randomized algorithm achieves expected linear time in the comparison model; it is a theorem cited here, not the code we just timed. Boruvka's simultaneous choices also motivate parallel and distributed algorithms, whose communication costs require their own analysis.

11Flows and cutsGraduate3 min

A flow network is a graph of pipes, each with a capacity. The question is how much can flow from a source s to a sink t, with nothing lost along the way. Lester Ford and Delbert Fulkerson's method, from 1956: find any path from s to t with spare capacity on every pipe, push as much as its narrowest pipe allows, and repeat. The subtle part is the residual graph. Pushing flow along a pipe also creates the option of pushing it back, so a later path may cancel an earlier choice. Jack Edmonds and Richard Karp showed that always choosing a shortest path, by breadth-first search, bounds the number of rounds. Here four augmenting paths bring the flow to nineteen.

A flow and a cut can certify each other's optimality. A cut puts source s on one side and sink t on the other; add capacities of original arcs directed across it from the source side. Flow conservation makes the net flow crossing any cut equal the source value, so that value cannot exceed cut capacity. When the residual graph has no augmenting path, let S be its vertices reachable from s. Every original arc leaving S is saturated, and any positive flow entering S would create a residual arc leaving S, so no such return flow remains. Thus flow equals cut capacity. Here both are nineteen: ten from s to a, plus nine from b to d. Our output checks capacity constraints, conservation and this equality. That is the max-flow min-cut certificate, rather than an inference from the picture alone.

An augmenting-path rule affects the amount of work. This network carries two thousand units, but alternating zig-zag paths through its unit-capacity middle edge add only one unit each. A backward residual arc cancels previous flow; it is not a new original pipe. That prescribed unlucky sequence takes two thousand augmentations. Integer capacities ensure progress in integral units; arbitrary irrational capacities do not give the same termination guarantee for arbitrary path choices. Breadth-first augmenting paths take two on this example. The random sixty-vertex example separately reports its actual distinct directed arcs, not the number of attempted dictionary writes, and has a checked flow/cut certificate. The research chapter will distinguish almost-linear theoretical bounds from practical implementations.

12MatchingGraduate2 min

Flows solve matching. Put workers on the left and jobs on the right, with an edge whenever a worker can do a job, and ask for as many worker–job pairs as possible, no one used twice. Add a source feeding every worker and a sink fed by every job, give every pipe capacity one, and a maximum integer flow is exactly a maximum matching. The min-cut side says when everyone can be matched: Philip Hall's theorem, that every group of k workers must between them be able to do at least k jobs. And Dénes Kőnig's theorem, that the largest matching equals the smallest set of vertices touching every edge, is the max-flow min-cut theorem again.

Stable matching is a preference problem, not minimum-cost assignment. Assume equally sized sides with strict, complete preference lists. Each free proposer tries the best receiver not yet approached. Receivers keep their best offer so far and reject the rest. At termination everyone is matched and no pair prefers each other to their current partners. The example's proposal count is computed from these lists. A proposer who prefers another receiver must already have tried that receiver and been rejected; that receiver's held partner only improves. This rules out a blocking pair. The resulting stable matching is optimal for proposers among stable matchings, not among every conceivable assignment. Deferred acceptance influenced residency-market design, but actual residency systems add capacities, couples and other rules beyond this simple model.

Count proposals before drawing conclusions. We generate independent uniform complete preference permutations on both sides, use five fixed seeds per size and verify stability even at size one thousand. The table reports the sample mean. The n times harmonic-number column is an order n log n scale reference, not an exact finite expectation for this experiment. Minimum-cost assignment is different. On our fixed sixty-by-sixty cost matrix, the Hungarian algorithm returns a checked permutation and total, compared with a row-wise greedy assignment.

13Easy and hardGraduate2 min

Hamilton's 1857 puzzle asks for a cycle through every corner of a dodecahedron. The flattened drawing has twenty vertices, thirty edges and degree three everywhere; the producer checks these counts. Visit each vertex once and return to the start. A complete backtracking enumeration finds thirty distinct undirected cycles, treating reverse orientations and different starting positions as the same cycle. One checked solution is highlighted. Success on twenty vertices is not a polynomial-time guarantee. The general decision problem is NP-complete; whether it has a polynomial algorithm is part of P versus NP, not something this small experiment resolves.

Euler circuits and Hamiltonian cycles have different conditions. An Euler circuit uses every edge once. Connected non-isolated vertices and even degrees give a constructive test; our validated implementation takes expected order V plus E. A Hamiltonian cycle visits every vertex once, and deciding existence is NP-complete. Exponential algorithms do not all have base two: Bjorklund's randomized undirected Hamiltonicity algorithm is a historical example below that base. General weighted travelling salesman asks for the least-weight Hamiltonian cycle. We implement the classical Bellman-Held-Karp subset dynamic programme, with order two to the n times n squared time. That is an algorithm we can measure, not a claim that no refinements or special-case improvements exist.

The table reports complete runs on this host. Each Held-Karp time is the minimum of three trials on a fixed Euclidean instance. Every returned value is checked against an independent suffix recurrence, and the smaller cases also against all tours. The fifty-city figure extrapolates the classical two-to-the-n times n-squared model from one measured size. It is an illustration, not an execution or a reliable wall-time prediction. The model also needs exponentially many states. The Euler timing includes incidence validation, and each of the three returned circuits is checked against all one hundred and eighty thousand edges. Practical exact solvers exploit structure and bounds on many large instances. That success is compatible with the absence of a known polynomial worst-case algorithm.

14PageRankIndustry2 min

PageRank assigns a stationary probability in a specified random-surfer model. With probability zero point eight five, follow a uniformly chosen outgoing link; otherwise jump uniformly to any page. At a page with no outgoing links, distribute its rank uniformly too. The equation includes all three contributions: teleportation, linked incoming rank, and dangling-page rank. That last term is needed for the small graph drawn here. Circle sizes encode the computed stationary probabilities, not a direct measurement of human importance. For damping strictly below one and uniform teleportation on a nonempty finite graph, the stationary vector is unique and power iteration converges. It is a model with a mathematical guarantee, rather than a guarantee of ranking quality.

Power iteration repeatedly applies the full surfer operator. Start with uniform rank, scan every link and redistribute dangling mass in each round. The green curve is the L1 change between successive vectors. Damping zero point eight five gives an L1 contraction bound: changes are at most zero point eight five times the preceding change. The dashed curve is a bound scaled from the first observed change, not an exact error trajectory. We check the final vector with a separate numerical operator, verify probability mass and compute its stationarity residual. Dividing that residual by one minus damping bounds distance to the stationary vector. A small iterate change is not itself proof that every pair of pages has a settled ordering.

This ranking belongs to a synthetic graph. The reported overlap compares its top ten by PageRank with its top ten by incoming-link count. Preferential attachment makes old popular pages attractive to new links, so this generator naturally couples those two measures. It is not a measurement of today's web. PageRank weights links according to the linking page's rank, which differs from merely counting incoming links. That difference does not make the system immune to manipulation: link farms and other adversarial strategies require additional ranking signals and defenses, as Part 47 discusses.

15Planar graphs and four coloursGraduate3 min

A planar graph admits a drawing with no edge crossings except at common endpoints. For a connected plane graph, counting the outer face, Euler's formula is vertices minus edges plus faces equals two. The cube gives eight minus twelve plus six. With c components the corresponding total is one plus c. Our connected triangulated grid is checked against the same formula. For a simple planar graph with at least three vertices, counting face-boundary incidences gives at most three V minus six edges; multiple edges and loops need different qualifications. The average degree is below six, so some vertex has degree at most five; this remains true in every simple planar subgraph. The complete graph on five vertices violates the bound and is not planar.

Map colouring requires regions sharing a border segment to differ; meeting only at a point does not count. For ordinary connected regions the adjacency graph is planar. Guthrie's 1852 question asked whether four colours always suffice. The five-colour theorem has a short inductive proof using the low-degree vertex and Kempe chains. Appel and Haken's 1976 four-colour proof used a finite reducibility computation; it was not just a search for colourings of a few maps. Gonthier's later Coq development formalized and machine-checked a four-colour proof. Our backtracking illustration is separate from those theorem proofs, and does not recreate their configuration checks.

The five-colour proof uses the cyclic order of neighbours in a planar drawing. Remove a vertex v of degree at most five and colour the smaller graph by induction. If its neighbours use at most four colours, one of five is free for v. Otherwise number the five differently coloured neighbours around v. If the connected one-three colour component of neighbour one avoids neighbour three, swap those two colours throughout that component. Colour one becomes free. If the component connects neighbours one and three, choose a simple path in it. Together with v it forms a separating cycle, so a two-four colour path cannot join neighbours two and four without crossing. Swap the two-four component containing neighbour two instead. A colour is free in either case. The chain idea comes from Kempe; Heawood identified the flaw in Kempe's four-colour argument and established the five-colour theorem.

Now our triangulated map. Greedy colouring visits the vertices in order and gives each the smallest colour its coloured neighbours do not use. It needs 5 colours here: this circled vertex took the fifth. Greedy is fast but not optimal. A backtracking search, which always colours the most constrained vertex next and undoes choices that lead nowhere, finds a colouring with four. It also proves that three are not enough: the map contains a vertex whose five neighbours form a cycle, and an odd cycle needs three colours on its own, leaving none for the centre. Four colours always exist and are found in quadratic time. But deciding whether three suffice is NP-complete, even for planar graphs.

16Research results: models and datesResearch3 min

First distinguish distance ordering from distance computation. Standard Dijkstra processes vertices in nondecreasing source distance, so its settlement order also sorts reachable distances. In the comparison model, some graph families encode a sorting problem; that is not a lower bound of n log n for every individual graph. Haeupler and colleagues' 2024 universal-optimality result concerns distance ordering on each fixed graph, compared against algorithms facing that graph's worst-case arc lengths in the specified model. It uses a heap with a working-set guarantee. Our ordinary Python binary heap is not an implementation of that specialized structure. Computing only the distances is a different output task, which is why the next results can improve sparse-graph bounds without contradicting this theorem.

These are selected dated results, not measurements of our city code. In 2025 Duan, Jiayi Mao, Xiao Mao, Shu and Yin gave a deterministic distance-only algorithm for directed graphs with nonnegative real weights. Its comparison-addition bound is m times log n to the two-thirds. A 2026 result by Duan, Xiao Mao, Shu and Yin improves the bound shown here; for sparse graphs it simplifies to m times the square root of log n times log log n. The bibliography identifies the ICALP publication and version. Frontier reduction combines limited relaxation with selective ordering. This episode does not implement either research algorithm. Negative weights need their own model: Bernstein, Nanongkai and Wulff-Nilsen's randomized result uses integer weights and includes a log W dependence, rather than covering arbitrary real weights at the same cost.

An almost-linear flow theorem also comes with conditions. Chen and colleagues' 2022 result gives exact directed maximum flow and minimum-cost flow in m to the one plus little o of one for polynomially bounded integral capacities, costs and demands in its stated setting. The method combines interior-point optimization with dynamic graph structures for approximate minimum-ratio cycles, whose update guarantee is amortized and subpolynomial. This is not a claim that every graph update costs constant time. Almost-linear describes asymptotic growth under those assumptions. It neither covers arbitrary real input for free nor promises that this implementation is as fast as reading a graph. The practical algorithm and its constants remain separate engineering questions.

The model determines the open question. Can directed nonnegative-real single-source distances be computed in order m plus n in the comparison-addition model, without sorted output? The plus n accounts for vertices even when there are few edges. Thorup's classical linear bound concerns undirected positive integer weights in a different model. Can almost-linear exact flow methods become practical under useful input assumptions? For general weighted all-pairs shortest paths, is a fixed polynomial improvement below cubic possible in the stated model? For general weighted TSP, can a classical algorithm achieve a base strictly below two, ignoring polynomial factors? This differs from unweighted Hamiltonicity and quantum computation. The research exercise takes the first question and asks you to keep its weight, output and machine model explicit.

Recap, problems, and where this comes backAll tracks3 min

We built checked examples of Euler circuits, breadth-first layers and bipartiteness; depth-first intervals and edge classes; topological orders, strong components and two-SAT. We proved Dijkstra's nonnegative-weight invariant, explored negative edges and reweighting, and compared actual route-search expansions on one synthetic city. Spanning-tree exchanges, feasible flows and matching certificates show how a proof can accompany an answer. Subset dynamic programming, damped PageRank and planar colouring illustrate different guarantees.

Where this comes back. Part 19 turns Floyd–Warshall and Held–Karp into a general method, dynamic programming. Part 20 studies random walks and finds minimum cuts by randomly contracting edges. Part 23 shows that max flow and min cut are dual linear programs. Part 26 is about Hamiltonian cycles, three-colouring and NP-completeness, and Part 27 about the all-pairs conjecture. The internet's routing in Part 36 runs Bellman–Ford and Dijkstra across routers, Part 35's databases plan queries over graphs, and Part 47's search engine ranks the web.

In practice, routing systems may use contraction hierarchies, landmark bounds, other preprocessing or direct searches, depending on updates and objectives. Build systems combine dependency ordering with caching and invalidation. OSPF uses shortest-path computation on link-state data, while BGP adds path attributes and policy; it is not simply a shortest numeric-distance solver. Graph databases and fraud analysis use reachability, cycles and neighbourhood queries. These algorithms are useful building blocks whose application assumptions still need checking.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: Dijkstra in the Pebble language, on the emulator, counting instructions per edge. The last, marked with a star, is a research problem: its answer is not known, and the notes say where to start.

Next time. This part used several design ideas without naming them: divide and conquer, greedy choices, dynamic programming, search. Part 19 makes them methods: the fast Fourier transform and the closest pair of points, when greedy choices are provably right, dynamic programming from edit distance to knapsack, and backtracking. Part 19, The Great Paradigms.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 19 turns Floyd-Warshall and Held-Karp into a general method, dynamic programming. Part 20 finds minimum cuts by contracting random edges, Part 23 shows that max flow and min cut are dual linear programs, Part 26 is about Hamiltonian cycles and NP-completeness, the internet's routing in Part 36 runs Bellman-Ford and Dijkstra across routers, and Part 47's search engine ranks the web.

Key results

The part's results in one place, for revision.

Euler's theorem (connected multigraphs)\(\displaystyle \text{an }\allowbreak \text{Euler }\allowbreak \text{circuit }\allowbreak \text{exists}\iff\text{every }\allowbreak \text{degree }\allowbreak \text{is }\allowbreak \text{even}\)
Dijkstra's invariant\(\displaystyle w\ge 0:\quad\allowbreak \text{when } u \text{ is }\allowbreak \text{settled},\ d(u)=\delta(s,u)\)
A* is exact when\(\displaystyle \text{priority}=d(v)+h(v),\qquad\allowbreak h(v)\le\delta(v,t),\quad\allowbreak h(t)=0\)
Cut property\(\displaystyle e \text{ uniquely }\allowbreak \text{lightest }\allowbreak \text{across }\allowbreak \text{a }\allowbreak \text{cut}\ \Longrightarrow\ e\in\text{every }\allowbreak \text{MST}\)
Max-flow min-cut\(\displaystyle \max_f |f|=\min_{(S,T)} c(S,T)\)
PageRank (D is the rank held by dangling pages)\(\displaystyle r_v=\frac{1-d+dD}{n}+d\sum_{u\to v}\frac{r_u}{\deg^{+}(u)}\)

Try it

Lab 18 · Exact routes with less search, and flows certified by cuts

On a seeded city of 1,200 intersections built by the series' generator, answer thirty route queries with Dijkstra, bidirectional Dijkstra and A*, check that all three return the same distance, and count the vertices each expands. Then run Edmonds-Karp on random networks and compare the flow with the smallest cut among all 1,024 ways to split the vertices; and build a spanning tree two ways.

Figure produced by Lab 18: Exact routes with less search, and flows certified by cuts
Produced by the lab below, seed 0, in 4.5 s.
python -m videos.cs.labs 18 needs numpy, scipy, matplotlib · download lab18.py · source on GitHub
city                                   1,200 intersections, 2,173 streets, 30 queries
same distance from all three searches  30 of 30
vertices expanded per query            Dijkstra 670   bidirectional 292   A* 225
max flow = smallest of 1,024 cuts      25 of 25 networks   (values 3 to 22)
augmenting paths per network           4.1 on average
minimum spanning tree of the city      Kruskal 948.040   Prim 948.040   (1,199 edges)

A lower bound on the remaining distance lets A* ignore most of the city without giving up exactness, and a flow is proved maximum by exhibiting a cut of the same value: no cut among all of them is smaller.
The code (123 lines; it asserts its own result)
"""Lab 18: route across a city with Dijkstra and A*, and certify maximum flows by cuts found by brute force."""

from videos.coursekit import labs
import itertools
import math

import numpy as np

from explainer.cs.algo import graphs

TITLE = "Exact routes with less search, and flows certified by cuts"
GOAL = ("On a seeded city of 1,200 intersections built by the series' generator, answer thirty route queries with "
        "Dijkstra, bidirectional Dijkstra and A*, check that all three return the same distance, and count the "
        "vertices each expands. Then run Edmonds-Karp on random networks and compare the flow with the smallest "
        "cut among all 1,024 ways to split the vertices; and build a spanning tree two ways.")
TASKS = [
    "Multiply A*'s estimate by 3 (so it can overestimate). Find a query whose route gets longer, and count the vertices expanded.",
    "Give one street a negative length and compare graphs.dijkstra with graphs.bellman_ford from the same source. Which distances differ?",
    "Replace graphs.edmonds_karp by graphs.ford_fulkerson_dfs on the same networks. Is the flow value the same? Is the number of augmenting paths?",
]
QUERIES, NETWORKS, FAST = 30, 25, 0.35  # FAST: the cheapest cost per unit of distance (the arterial roads)


def network(rng, n=12, arcs=34):
    """A random directed network on n vertices with integer capacities; 0 is the source and n - 1 the sink."""
    cap = {u: {} for u in range(n)}
    for u in range(n - 1):  # a path through every vertex, so the sink can be reached
        cap[u][u + 1] = int(rng.integers(1, 10))
    for _ in range(arcs):
        u, v = (int(x) for x in rng.choice(n, 2, replace=False))
        cap[u][v] = int(rng.integers(1, 10))
    return cap


def smallest_cut(cap):
    """The least capacity leaving S, over every vertex set S that holds the source and not the sink."""
    n = len(cap)
    best = math.inf
    for mask in itertools.product((False, True), repeat=n - 2):
        S = {0} | {u + 1 for u, inside in enumerate(mask) if inside}
        best = min(best, sum(c for u in S for v, c in cap[u].items() if v not in S))
    return best


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. thirty exact routes, three ways
    adj, pos = graphs.grid_city(40, 30, rng)
    reached = graphs.bfs(adj, (0, 0), weighted=True)[0]  # keep the part of the city joined to the corner
    adj = {u: nbrs for u, nbrs in adj.items() if u in reached}
    verts = list(adj)
    rows, picture = [], None
    for _ in range(QUERIES):
        s, t = (verts[int(i)] for i in rng.choice(len(verts), 2, replace=False))
        plain, astar = [], []
        dist, _, n_dij, _ = graphs.dijkstra(adj, s, t, settled_order=plain)
        dist_a, _, n_ast, _ = graphs.dijkstra(adj, s, t, lambda v, t=t: FAST * math.dist(pos[v], pos[t]),
                                              settled_order=astar)
        dist_b, n_bi = graphs.bidijkstra(adj, adj, s, t)  # the streets are two-way: the reverse graph is the graph
        assert abs(dist[t] - dist_a[t]) < 1e-9 and abs(dist[t] - dist_b) < 1e-9, "three searches, three distances"
        rows.append((n_dij, n_bi, n_ast, dist[t]))
        if picture is None or n_dij - n_ast > picture[0]:  # draw the query where the bound saves most
            picture = (n_dij - n_ast, s, t, plain, astar)
    counts = np.array([r[:3] for r in rows])
    mean = counts.mean(axis=0)
    lab.row("city", f"{len(adj):,} intersections, {sum(len(a) for a in adj.values()) // 2:,} streets, {QUERIES} queries")
    lab.row("same distance from all three searches", f"{QUERIES} of {QUERIES}")
    lab.row("vertices expanded per query", f"Dijkstra {mean[0]:.0f}   bidirectional {mean[1]:.0f}   A* {mean[2]:.0f}")
    assert np.all(counts[:, 2] <= counts[:, 0]), "A* with a consistent bound never expands more than Dijkstra"
    assert mean[2] < 0.75 * mean[0] and mean[1] < 0.85 * mean[0], "the goal-directed searches should do less work"

    # 2. max flow = min cut, with the cut found by brute force
    flows = []
    for _ in range(NETWORKS):
        cap = network(rng)
        flow, paths, side = graphs.edmonds_karp(cap, 0, len(cap) - 1)
        certificate = sum(c for u in side for v, c in cap[u].items() if v not in side)
        brute = smallest_cut(cap)
        assert flow == certificate == brute, f"flow {flow}, its cut {certificate}, the smallest cut {brute}"
        assert flow == sum(b for _, b in paths)
        flows.append((flow, brute, len(paths)))
    lab.row("max flow = smallest of 1,024 cuts", f"{NETWORKS} of {NETWORKS} networks   "
                                                 f"(values {min(f[0] for f in flows)} to {max(f[0] for f in flows)})")
    lab.row("augmenting paths per network", f"{np.mean([f[2] for f in flows]):.1f} on average")

    # 3. one tree, two algorithms
    index = {v: i for i, v in enumerate(verts)}
    edges = [(w, index[u], index[v]) for u in adj for v, w in adj[u] if index[u] < index[v]]
    by_index = {index[u]: [(index[v], w) for v, w in adj[u]] for u in adj}
    kruskal, tree = graphs.kruskal(len(verts), edges)
    prim, _ = graphs.prim(len(verts), by_index)
    lab.row("minimum spanning tree of the city", f"Kruskal {kruskal:.3f}   Prim {prim:.3f}   ({len(tree):,} edges)")
    assert abs(kruskal - prim) < 1e-6 and len(tree) == len(verts) - 1
    lab.note = ("A lower bound on the remaining distance lets A* ignore most of the city without giving up "
                "exactness, and a flow is proved maximum by exhibiting a cut of the same value: no cut among all "
                "of them is smaller.")

    fig, ax = labs.figure(2, size=(11, 4.6))
    _, s, t, plain, astar = picture
    for u in adj:
        for v, _ in adj[u]:
            if index[u] < index[v]:
                ax[0].plot([pos[u][0], pos[v][0]], [pos[u][1], pos[v][1]], color=labs.GRID, lw=0.6, zorder=1)
    for pts, color, size, label in ((plain, labs.BLUE, 9, f"Dijkstra expands {len(plain)}"),
                                    (astar, labs.GOLD, 5, f"A* expands {len(astar)}")):
        ax[0].scatter([pos[v][0] for v in pts], [pos[v][1] for v in pts], s=size, color=color, label=label, zorder=2)
    ax[0].scatter(*pos[s], s=70, color=labs.INK, edgecolor=labs.BG, zorder=4, label="source")
    ax[0].scatter(*pos[t], s=70, color=labs.RED, edgecolor=labs.BG, zorder=4, label="target")
    ax[0].set(title="One query: the intersections each search expands", xticks=[], yticks=[])
    ax[0].grid(False)
    ax[0].legend(loc="upper center", bbox_to_anchor=(0.5, -0.02), ncols=4, fontsize=8, handletextpad=0.3,
                 columnspacing=1.0)
    top = counts[:, 0].max() * 1.05
    ax[1].plot([0, top], [0, top], color=labs.GREY, ls="--", lw=1, label="as much work as Dijkstra")
    ax[1].scatter(counts[:, 0], counts[:, 1], s=20, color=labs.GREEN, label="bidirectional Dijkstra")
    ax[1].scatter(counts[:, 0], counts[:, 2], s=20, color=labs.GOLD, label="A* (straight-line bound)")
    ax[1].set(title=f"Vertices expanded on {QUERIES} queries", xlabel="Dijkstra", ylabel="the other search",
              xlim=(0, top), ylim=(0, top))
    ax[1].legend(loc="upper left")
    lab.fig = fig
    return lab

Now change it

  1. Multiply A*'s estimate by 3 (so it can overestimate). Find a query whose route gets longer, and count the vertices expanded.
  2. Give one street a negative length and compare graphs.dijkstra with graphs.bellman_ford from the same source. Which distances differ?
  3. Replace graphs.edmonds_karp by graphs.ford_fulkerson_dfs on the same networks. Is the flow value the same? Is the number of augmenting paths?

Problems, with solutions

Try each problem before opening its solution.

  1. Euler circuits. Prove that a connected graph in which every vertex has even degree has an Euler circuit, and that Hierholzer's algorithm finds one in O(V + E), including adjacency validation.

    Solution

    Necessity first: a circuit leaves every vertex as often as it enters, so it uses an even number of edges at each vertex. For sufficiency, start anywhere and walk along unused edges. Each time the walk enters a vertex v ≠ start it has used an odd number of v's edges, so an unused one remains; the walk can therefore only get stuck at the start, and it closes a circuit C. If C misses edges, some vertex u on C has an unused edge, since the graph is connected. Every degree in the unused graph is still even, because C used an even number at each vertex. Walk from u in the unused edges to get a circuit C′ through u, and splice C′ into C at u. Repeat until no edge is unused. Hierholzer's algorithm does the splicing with a stack: push the current vertex; while the top has an unused edge, follow it and push; otherwise pop the top onto the output. Each edge is followed once and each vertex pushed and popped once per use, so with a pointer into each adjacency list the work is O(V + E).

  2. BFS. Prove that breadth-first search dequeues vertices in non-decreasing order of distance from the source, and deduce that the BFS tree contains a shortest path to every reachable vertex.

    Solution

    Claim: at every moment the queue holds vertices with labels d(v₁) ≤ d(v₂) ≤ … ≤ d(v_k) ≤ d(v₁) + 1. This holds initially (only s, label 0). Dequeuing v₁ keeps it. Each vertex enqueued while scanning v₁ gets label d(v₁) + 1, which is at least d(v_k) and at most d(v₂) + 1, since d(v₂) ≥ d(v₁). So labels leave the queue in non-decreasing order. Now show d(v) = δ(v), the true distance. The label is the length of a real path (the tree path), so d(v) ≥ δ(v). Suppose some vertex has d(v) > δ(v); take one with δ(v) smallest, and let u be its predecessor on a shortest path, so δ(u) = δ(v) − 1 = d(u). When u was dequeued, v was either undiscovered (then it gets d(u) + 1 = δ(v), a contradiction), or already in the queue or dequeued, with label at most d(u) + 1 by the claim, again a contradiction. So the tree path to every v has length δ(v).

  3. Negative edges and reweighting. Show that Dijkstra's algorithm can fail with a single negative edge, and that Johnson's reweighting w′(u, v) = w(u, v) + p(u) − p(v) preserves every shortest path.

    Solution

    Take edges s → a of weight 2, s → b of weight 3 and b → a of weight −2. Dijkstra settles a at distance 2 before b, and never revisits it, but s → b → a costs 1. For reweighting, take any path P = v₀ → v₁ → … → v_k. The p terms telescope: w′(P) = w(P) + p(v₀) − p(v_k). Every path from v₀ to v_k changes by the same constant, so the shortest ones stay shortest, and cycles keep their weight, so negative cycles stay negative. Johnson takes p(v) = δ(q, v), distances from a new vertex q joined to every vertex by a zero edge, computed by Bellman–Ford. The triangle inequality δ(q, v) ≤ δ(q, u) + w(u, v) is exactly w′(u, v) ≥ 0, so Dijkstra can then run from every vertex: O(VE + V(V + E) log(V + E)) in all.

  4. The cut property. Prove that for any cut of a connected weighted graph, a lightest edge crossing it belongs to some minimum spanning tree, and deduce that Kruskal's and Prim's algorithms are correct.

    Solution

    Let A be a set of edges contained in some MST T, let the cut (S, V − S) cross no edge of A, and let e be a lightest edge crossing it. If e ∈ T we are done. Otherwise T + e contains a cycle through e, and the cycle crosses the cut at least twice, so it contains another crossing edge f ∉ A. Then T′ = T + e − f is a spanning tree, and w(e) ≤ w(f), so w(T′) ≤ w(T): T′ is an MST containing A + e. Prim grows one tree, and at each step adds a lightest edge crossing the cut between that tree and the rest. Kruskal adds the lightest remaining edge that joins two different components; it is a lightest edge crossing the cut between one of those components and everything else. By induction, every edge either algorithm adds keeps A inside some MST, and it ends with V − 1 edges, a spanning tree, so the tree is minimum.

  5. Build: Dijkstra on Pebble. Implement a lazy binary-heap query on the emulator, using a compressed sparse-row graph and precisely specified integer edge weights. Compare binary and four-ary heaps.

    Solution

    Solution protocol. Scale each synthetic road weight by 1,000 and round once; the reference must use those same integers, not the original floats. Store row offsets, targets and weights, with capacities large enough for every adjacency entry and every lazy heap push. On popping an entry, skip it if its stored distance is stale. Count scans, pushes, pops, comparisons and retired instructions, and check every resulting distance against an independent shortest-path reference. Keep initialization inside or outside both timing windows consistently. A four-ary heap has fewer levels but compares more children per level; measure the resulting instructions instead of predicting which wins. Use multiple graph sizes and report raw repeated runs.

  6. ★ Research: linear-time distance-only shortest paths. Find directed nonnegative-real single-source distances in O(m + n) in the comparison-addition model, without requiring sorted output, or prove a lower bound that rules it out. On a reachable graph with m = Ω(n), this is the usual O(m) target.

    Where to start. Separate distance ordering from a distance vector. The 2024 universal-optimality theorem fixes a graph and compares worst-case arc lengths for the ordering task, using a specified working-set heap. The 2025 deterministic nonnegative-real result gives O(m log^(2/3) n). A 2026 improvement gives O(m sqrt(log n) + sqrt(m n log n log log n)), simplifying on sparse graphs to O(m sqrt(log n log log n)). Read the stated assumptions and proofs before implementing a frontier-reduction component; compare all distances, not only the number of vertices entering an ordered structure. Thorup's classical linear result uses undirected positive integer weights in a different machine model.

Notes and sources

Glossary

图 graph · 顶点 vertex · 边 edge · 度 degree · 欧拉回路 Euler circuit · 邻接表 adjacency list · 邻接矩阵 adjacency matrix · 广度优先搜索 breadth-first search · 二分图 bipartite graph · 深度优先搜索 depth-first search · 括号定理 parenthesis theorem · 树边 tree edge · 回边 back edge · 前向边 forward edge · 横叉边 cross edge · 白色路径定理 white-path theorem · 有向无环图 directed acyclic graph · 拓扑排序 topological sort · 强连通分量 strongly connected component · 缩点图 condensation · 低链 low-link · 蝴蝶结结构 bow-tie structure · 2-可满足性 2-SAT · 单源最短路径 single-source shortest paths · 松弛 relaxation · 负回路 negative cycle · 套利 arbitrage · 全源最短路径 all-pairs shortest paths · 重新赋权 reweighting · 势函数 potential · 最小加乘积 min-plus product · 双向搜索 bidirectional search · 可采纳启发式 admissible heuristic · 地标 landmarks · 收缩层次 contraction hierarchies · 捷径边 shortcut · 最小生成树 minimum spanning tree · 割性质 cut property · 圈性质 cycle property · 流网络 flow network · 容量 capacity · 增广路径 augmenting path · 残量图 residual graph · 最大流最小割定理 max-flow min-cut theorem · 推送–重标记 push–relabel · 二分匹配 bipartite matching · 稳定匹配 stable matching · 指派问题 assignment problem · 匈牙利算法 Hungarian algorithm · 哈密顿回路 Hamiltonian cycle · 旅行商问题 travelling salesman problem · 随机冲浪者 random surfer · 平稳分布 stationary distribution · 幂迭代 power iteration · 平面图 planar graph · 四色定理 four colour theorem · 肯普链 Kempe chain · 普适最优 universal optimality

Sources

Selected primary research sources

These are dated model statements checked for this lesson, not an exhaustive literature review or a full proof audit. None of the new theoretical algorithms is implemented by the city benchmark.

The classical bibliography follows below; newer research bounds do not retroactively change the scope of the implemented algorithms or the recorded experiments.

Sources

Canon. Books: Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, chapters 20–26; Kleinberg & Tardos, Algorithm Design, chapters 3, 4 and 7; Tarjan, Data Structures and Network Algorithms (1983); Even, Graph Algorithms; Ahuja, Magnanti & Orlin, Network Flows (1993); Schrijver, Combinatorial Optimization (2003); Wilson, Four Colors Suffice (2002).

Papers: Euler, "Solutio problematis ad geometriam situs pertinentis" (1736); Hierholzer (1873); Kempe (1879); Heawood, "Map-colour theorem" (1890); Borůvka (1926); Kőnig (1931); Hall, "On representatives of subsets" (1935); Kuhn, "The Hungarian method for the assignment problem" (1955); Kruskal (1956); Ford & Fulkerson, "Maximal flow through a network" (1956); Elias, Feinstein & Shannon (1956); Prim (1957); Bellman, "On a routing problem" (1958); Moore, "The shortest path through a maze" (1959); Dijkstra, "A note on two problems in connexion with graphs" (1959); Floyd, "Algorithm 97" (1962); Warshall (1962); Held & Karp (1962); Kahn (1962); Gale & Shapley, "College admissions and the stability of marriage" (1962); Hart, Nilsson & Raphael (1968); Edmonds & Karp (1972); Tarjan, "Depth-first search and linear graph algorithms" (1972); Karp, "Reducibility among combinatorial problems" (1972); Appel & Haken (1976); Johnson (1977); Sharir (1981); Aspvall, Plass & Tarjan (1979); Fredman & Tarjan (1987); Goldberg & Tarjan (1988); Karger, Klein & Tarjan (1995); Robertson, Sanders, Seymour & Thomas (1996); Goldberg & Rao (1998); Page, Brin, Motwani & Winograd, "The PageRank citation ranking" (1998); Brin & Page (1998); Roth & Peranson (1999); Thorup (1999); Broder et al., "Graph structure in the web" (2000); Goldberg & Harrelson, "Computing the shortest path: A* search meets graph theory" (2005); Gonthier, "A computer-checked proof of the four colour theorem" (2005); Geisberger, Sanders, Schultes & Delling, "Contraction hierarchies" (2008); Bast et al., "Route planning in transportation networks" (2016).

About this partfrom its README

Part 18 of the sixty-one-part course. The lesson connects proofs to checked outputs: a circuit with an edge certificate, a shortest path with a settled-set invariant, a tree with an exchange argument, and a flow whose value equals a cut. English and Chinese narration share canonical source pairs. Visual previews, speech-signal checks and final listening/production approval have separate scopes.

The instrument is explainer/cs/algo/graphs.py; independent output checks and measurement protocols are in measurements.py, producers in compute.py, and regressions in tests/test_cs18_graphs.py.

What is computed and builtMeasurements and model limits

Ten schema revisions replace ten of sixteen original payloads; the original data and media remain in the local QA packet. Numerical producers verify complete outputs before reporting measurements. Cached-only QA rejects old schemas before entering the upgrading loader.

Experiment What is actually observed What the result does not establish
Representation Three complete scans of each fixed graph, minimum time; Python entry visits versus NumPy full boolean-row counts, both exactly 2E A packed-bit benchmark or a cache-level causal explanation
Storage Ideal eight-byte list entries/row references and packed bits; separately, reachable Python allocations and actual NumPy byte data Process RSS, allocator peak or a claim that NumPy bool packs bits
All pairs Same fixed potential-generated integer graph; all finite and unreachable pairs checked; three full runs per algorithm A fallback graph with negative edges silently removed
Routing Forty fixed queries; all five route distances checked; actual expansions, with both sides counted for bidirectional methods Query latency, phone performance or continental scaling
Preprocessing One hierarchy build and one reusable landmark-table build, stated separately A repeated timing comparison or per-query preprocessing cost
Stable matching Five uniform strict-preference trials per size, including stability checks at n = 1,000 An exact finite expected proposal count of nH_n; that column is a scale reference
TSP / Euler Three complete runs, minimum time; checked tour values and complete circuit edge multisets A measured 50-city run; that number is an explicitly illustrative 2^n n² extrapolation
PageRank Probability mass, successive L1 changes and a separately checked stationarity residual A guarantee of human relevance or that all page orderings have stabilized

On this retained run the dense 3,000-vertex graph has 1,500,000 undirected edges. Its ideal packed matrix is 1.125 MB, while the measured NumPy boolean data occupies 9 MB. The random flow network has 379 distinct directed arcs after 400 attempted writes, and its small example has certified flow/cut value 19. The routing means are about 2,525 / 1,237 / 657 / 212 / 113 expansions for Dijkstra / bidirectional / straight-line A* / landmarks / hierarchy, respectively. These are work counts on one synthetic graph.

For damping d = 0.85, dangling mass D is redistributed uniformly. The PageRank equation includes (1-d+dD)/n plus linked incoming rank. Its plotted change C_k satisfies C_(k+1) ≤ d C_k. The dashed curve is scaled from the first measured change. A final stationarity residual R bounds stationary-vector error by R/(1-d); a small iterate change is a different quantity. The retained 20,000-page run takes 52 rounds.

Historical web percentages from Broder et al.'s May 1999 crawl are distinct from the synthetic generator, whose outgoing-only component is empty. Fees, spreads and trade execution are omitted from the invented arbitrage example. A cycle in an application graph alone is not evidence of fraud. Real routing, residency matching and package managers add policies and constraints beyond these teaching models.

NotesWhat the chapters establish
  • Euler circuits in undirected multigraphs, including parallel edges, twice-listed loops, empty/edgeless inputs and isolated vertices. Edge identifiers avoid reverse-list deletion. Non-isolated vertices must connect; validation and traversal take expected O(V + E) using hash tables.
  • Adjacency-list and matrix models, BFS layers and odd-cycle witnesses, DFS intervals and edge classes, topological ordering, Tarjan/Kosaraju components, and two-SAT by comparing each literal's component with its negation.
  • Nonnegative-weight Dijkstra, reachable negative-cycle detection, Floyd–Warshall, Johnson reweighting with a collision-free fresh vertex, and min-plus products. Bellman–Ford uses floating arithmetic and a 1e-12 relaxation tolerance; near-zero cycles require numerical care. Not every routine performs full input validation.
  • Point-to-point routing with bidirectional search, A*, reusable landmark distances and contraction hierarchies. A* supports reopening for inconsistent admissible estimates with h(target) = 0. The city bounds are additionally checked consistent, so its expansion counts have no reopening. Panel dots are actual expansions, not parent-map keys.
  • MST exchange arguments, with a uniquely heaviest cycle edge excluded from every MST; tied maxima need care. Edmonds–Karp residual cancellation, capacity/conservation certificates, and max-flow/min-cut equality.
  • Unit-capacity matching, stable matching under strict complete balanced preferences, minimum-cost assignment, checked Bellman–Held–Karp subset DP, damped PageRank with dangling redistribution, and planar/Kempe-chain proofs.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Königsberg (1736): degrees 5, 3, 3, 3; the even-degree theorem (proved) and Hierholzer's circuit in O(E); adjacency lists against a matrix, measured from sparse to dense (the matrix wins at 1.5 million edges on 3,000 vertices).
  2. BFS: layers in a 24 × 14 maze (67 layers, a 59-cell path; Moore 1959); the queue lemma (proved, animated); bipartiteness and the odd cycle that refutes it.
  3. DFS: discovery and finish times; the parenthesis and white-path theorems; tree, back, forward and cross edges; a back edge is a cycle (Trémaux 1882; Hopcroft & Tarjan).
  4. Topological sort: a compiler's build graph by DFS finish order and by Kahn's queue (1962); cycles; make, spreadsheets, Part 13's reverse postorder, critical paths.
  5. SCCs: Tarjan's low links, traced step by step with the stack; Kosaraju; the condensation; a 20,000-page synthetic web (a core of 7,583) and Broder's bow tie; 2-SAT by the implication graph (Aspvall, Plass & Tarjan 1979).
  6. Dijkstra (1956/59): the invariant proved with the settled-set picture; Part 17's heap; the wavefront over a city of 2,400 intersections with arterial roads.
  7. Negative edges: Dijkstra's failure; Bellman–Ford round by round; negative cycles; arbitrage as a negative cycle in −log rates (illustrative rates: JPY → GBP → EUR, +0.5%); distance-vector routing (Part 36).
  8. All pairs: Floyd–Warshall as DP; Johnson's reweighting (proved, with a worked example; 150 vertices and 231 negative edges, matching Floyd–Warshall); the min-plus product and the APSP conjecture (Part 27).
  9. Route planning: A* (callback to AI, Built 2), landmarks, contraction hierarchies; vertices settled per query on 4,800 intersections: Dijkstra 2,525, bidirectional 1,237, A* 657, landmarks 212, CH 113.
  10. MSTs: the cut property, proved on a worked example, and the cycle property; Kruskal with Part 17's union–find, Prim/Jarník, Borůvka (1926, for the Moravian grid; 4 rounds); Karger, Klein & Tarjan.
  11. Max-flow min-cut: augmenting paths and the residual graph; the theorem (proved; 19 = 10 + 9); Edmonds–Karp against an unlucky path choice (2 augmentations against 2,000); push–relabel.
  12. Matching: bipartite matching as flow; Hall and Kőnig; Gale–Shapley with stability proved; proposals against n Hₙ; the Hungarian algorithm (166 against greedy's 308).
  13. Easy and hard: Hamilton's icosian game (all 30 Hamiltonian cycles of the dodecahedron); Euler against Hamilton (Part 26); Held–Karp timed against brute force.
  14. PageRank (Brin & Page 1998): the random surfer's stationary distribution (callback to AI, Built 5); power iteration on 20,000 pages (52 rounds to 10⁻¹²); rank against in-degree.
  15. Planarity: V − E + F = 2 (54 − 133 + 81); E ≤ 3V − 6 and K₅; Guthrie to Appel–Haken (1976) and Gonthier's Coq proof (2005); the five-colour theorem by Kempe chains (proved, animated); our map coloured greedily with 5, with 4 by backtracking, and 3 refuted by an odd wheel.
  16. Frontier: universally optimal Dijkstra (Haeupler, Hladík, Rozhoň, Tarjan & Tětek, FOCS 2024); directed SSSP in O(m log^{2/3} n), beyond the sorting barrier (Duan, Mao, Mao, Shu & Yin, STOC 2025); negative weights in near-linear time (Bernstein, Nanongkai & Wulff-Nilsen 2022); max flow in almost-linear time (Chen, Kyng, Liu, Peng, Probst Gutenberg & Sachdeva 2022); open problems. Outro.

Computed: every number above, in videos/cs/cs18/compute.py with explainer/cs/algo/graphs.py (tested in tests/test_cs18_graphs.py): BFS, DFS and SCC traces; the representation timings; Dijkstra, bidirectional, A*, ALT and CH on one city; Bellman–Ford, Floyd–Warshall and Johnson; Kruskal, Prim and Borůvka; Edmonds–Karp; Gale–Shapley and the Hungarian algorithm; Held–Karp; PageRank; planar colouring. Visuals: the Königsberg multigraph; the BFS flood and its queue; DFS stamps and parentheses; Tarjan's stack; the Dijkstra wavefront and settled-set proof; search footprints for A*, landmarks and CH; the cut-property swap; flows as flashes along paths, and the min cut; Kempe chains. In practice: route planning in maps, network routing, dependency graphs, social graphs, scheduling, graph databases. Reading: CLRS ch. 20–26; Kleinberg & Tardos ch. 3, 4, 7; Tarjan; Ahuja, Magnanti & Orlin, Network Flows; Even, Graph Algorithms; Schrijver, Combinatorial Optimization; Dijkstra 1959; Ford & Fulkerson 1956; Tarjan 1972; Gale & Shapley 1962; Chen et al. 2022; Haeupler et al. 2024; Duan et al. 2025.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 欧拉回路。 证明:所有顶点度数都为偶数的连通图有欧拉回路,并且 Hierholzer 算法能在 O(V + E) 时间(包含邻接校验)内找到它。

    解答

    先证必要性:回路离开每个顶点的次数等于进入的次数,所以在每个顶点用掉偶数条边。再证充分性:从任意顶点出发, 沿未用过的边走。每次走进一个不是起点的顶点 v 时,v 的边已用掉奇数条,所以还剩一条没用;因此只可能在起点卡住,走出的 是一条回路 C。如果 C 漏掉了边,由于图连通,C 上有某个顶点 u 还有未用的边。未用边构成的图中每个度数仍是偶数,因为 C 在每个 顶点用掉偶数条。从 u 出发在未用边中走出一条过 u 的回路 C′,在 u 处把 C′ 接进 C。重复直到没有未用的边。Hierholzer 算法用 一个栈完成拼接:把当前顶点压栈;栈顶还有未用边时,沿它走并压栈;否则把栈顶弹出到输出。每条边只走一次,每个顶点每用一次 就压栈、出栈一次,所以给每个邻接表配一个指针,总工作量是 O(V + E)。

  2. 广度优先搜索。 证明广度优先搜索按到源点距离的非降顺序出队,并推出 BFS 树包含到每个可达顶点的最短路径。

    解答

    断言:任何时刻队列中的顶点标号满足 d(v₁) ≤ d(v₂) ≤ … ≤ d(v_k) ≤ d(v₁) + 1。开始时成立(只有 s,标号 0)。 v₁ 出队后仍成立。扫描 v₁ 时入队的每个顶点标号为 d(v₁) + 1,它不小于 d(v_k),且由于 d(v₂) ≥ d(v₁),不大于 d(v₂) + 1。 所以标号按非降顺序出队。再证 d(v) = δ(v)(真实距离)。标号是一条真实路径(树上路径)的长度,所以 d(v) ≥ δ(v)。假设有 顶点 d(v) > δ(v),取其中 δ(v) 最小的一个,设 u 是它某条最短路径上的前驱,则 δ(u) = δ(v) − 1 = d(u)。u 出队时,v 要么尚未 发现(这时得到 d(u) + 1 = δ(v),矛盾),要么已在队中或已出队,由断言其标号至多 d(u) + 1,同样矛盾。所以到每个 v 的树上 路径长度都是 δ(v)。

  3. 负边与重新赋权。 说明一条负边就能让 Dijkstra 算法出错,并证明 Johnson 的重新赋权 w′(u, v) = w(u, v) + p(u) − p(v) 保持所有最短路径不变。

    解答

    取边 s → a 权 2、s → b 权 3、b → a 权 −2。Dijkstra 在 b 之前以距离 2 定下 a,之后不再回头,但 s → b → a 只要 1。 关于重新赋权,任取路径 P = v₀ → v₁ → … → v_k,p 项逐项相消:w′(P) = w(P) + p(v₀) − p(v_k)。从 v₀ 到 v_k 的每条路径都改变同一个 常数,所以最短的仍是最短的;回路的权不变,所以负回路仍是负的。Johnson 取 p(v) = δ(q, v),即从一个新顶点 q(用零权边连到 每个顶点)出发、由 Bellman–Ford 算出的距离。三角不等式 δ(q, v) ≤ δ(q, u) + w(u, v) 正好就是 w′(u, v) ≥ 0,于是可以从每个顶点 运行 Dijkstra:总计 O(VE + V(V + E) log(V + E))。

  4. 割性质。 证明:对连通带权图的任一割,穿过它的最轻边属于某棵最小生成树;并由此推出 Kruskal 算法和 Prim 算法正确。

    解答

    设边集 A 包含在某棵最小生成树 T 中,割 (S, V − S) 不穿过 A 的任何边,e 是穿过它的最轻边。若 e ∈ T,结论成立。 否则 T + e 含有一个经过 e 的圈,这个圈至少两次穿过割,所以含有另一条穿过割的边 f ∉ A。于是 T′ = T + e − f 是生成树,且 w(e) ≤ w(f),所以 w(T′) ≤ w(T):T′ 是包含 A + e 的最小生成树。Prim 只长一棵树,每步加入穿过"这棵树与其余顶点"之割的最轻 边。Kruskal 加入连接两个不同连通分量的最轻剩余边;它是穿过"其中一个分量与其余一切"之割的最轻边。归纳可知,两个算法 加入的每条边都使 A 仍在某棵最小生成树之中,而它们结束时恰有 V − 1 条边,构成生成树,所以这棵树是最小的。

  5. 动手:在 Pebble 上跑迪杰斯特拉。 用压缩稀疏行存图,在模拟器上实现惰性二叉堆查询,并比较二叉堆和四叉堆。

    解答

    解答方案。 把每条合成道路权值乘一千后只取整一次,参考算法必须使用完全相同的整数,而非原浮点权值。 为全部邻接条目及所有惰性堆插入准备足够容量。弹出时,若存储距离已过期就跳过。分别数扫描、压入、弹出、比较和退休指令, 并把每个结果距离与独立参考比较。两种实现的计时窗口必须一致地包含或排除初始化。四叉堆层数较少,但每层比较更多子节点; 要测量指令数,而不是预言谁会赢。使用多个图规模,保存重复运行的原始结果。

  6. ★ 研究题:只求距离的线性时间最短路径。 在比较加法模型中,以 O(m+n) 时间求非负实数权有向单源距离, 不要求按距离排序输出,或证明排除这一算法的下界。在 m=Ω(n) 的可达图中,这就是通常的 O(m) 目标。

    起点。 区分距离顺序与距离向量。2024年的普适最优性定理固定图、比较最坏弧长,针对排序任务并使用特定工作集堆。 2025年的确定性非负实数权结果为 O(m log^(2/3)n)。2026年的改进为 O(m sqrt(log n)+sqrt(mn log n log log n)),稀疏图可简化为 O(m sqrt(log n log log n))。 实现前沿缩减的一个环节前,应先阅读明确假设和证明;比较全部距离,而不只统计进入有序结构的顶点数。 索鲁普经典的线性结果针对另一机器模型中的无向正整数权图。

Build the film

python -m videos.cs.cs18.compute        # the part's numbers, into .cache/cs18
python tools/build.py cs18                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs18 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs18. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs18.compute
python -m unittest tests.test_cs18_graphs -v
python tools/build.py cs18 -q l
python tools/build.py cs18

After a producer schema change, recompute its affected items explicitly with --force. A native master is not approved by sampled previews; continuous audiovisual/listening review and Chinese synthesized-speech review remain separate release gates.