Module contents
Lesson 16 of 22Advanced 100 min

Matchings, colouring, planarity and Ramsey theory

Classical structural results with certificates in both directions: Hall's and König's theorems for matchings, graph coloring and chromatic number, planar graphs and Euler's formula, and Ramsey theory with Erdős's probabilistic bound. The four-color theorem bridges to computer-assisted proof.

After this lesson you can

  • Prove Hall's theorem and extract a violating set when no perfect matching exists.
  • Apply König's theorem and connect it to min-max duality.
  • Bound the chromatic number and analyze order dependence in greedy coloring.
  • Use Euler's formula to prove that K5 and K3,3 are nonplanar.
  • Prove upper and lower bounds for Ramsey numbers, including the probabilistic bound.

Before you start

Motivation: assign, schedule, draw

Three problems that arise when managing a real system:

  • Assign jobs to GPUs. You have six training jobs and six GPUs, but not every job fits every GPU: some need 80 GB of memory, others a particular architecture, others a machine in a particular region. Is there an assignment placing each job on a distinct GPU? The same problem appears under other names when distributing papers to reviewers without conflicts of interest or assigning candidates to positions.
  • Schedule exams or allocate registers. Two exams sharing a student cannot use the same time slot; two variables live at the same time cannot share a processor register. How many slots or registers are needed? This is graph coloring: compilers have allocated registers this way since Chaitin’s work in the early 1980s.
  • Draw without crossings. A single-layer printed circuit, a subway network plan, or a political map: can the connections be drawn without crossing?

This lesson’s theorems answer these questions and share a thread worth keeping in mind from the start: certificates. When an algorithm says “yes, there is an assignment,” it can give you the assignment, which is trivial to check. But when it says “there is none,” how do you check without repeating the entire search? Hall’s theorem gives a short “no” certificate for assignments; König’s turns a maximum into an exhibitable minimum; Euler’s formula certifies that certain graphs cannot be drawn without crossings without trying any drawing. Coloring, by contrast, is a case where no short “no” certificate is known: deciding whether a graph is 3-colorable is NP-complete. Ramsey theory closes the lesson with the opposite extreme: an existence proof that constructs nothing.

Everything that follows uses the vocabulary of the graph lesson: degrees, paths and connectivity, and above all bipartite graphs. We write N(v)N(v) for the neighbors of vv and N(S)=⋃v∈SN(v)N(S) = \bigcup_{v \in S} N(v) for the neighborhood of a set.

Matchings and augmenting paths

Distinguish two notions everyday language confuses. A matching is maximal if no edge can be added, and maximum if no other has more edges. Every maximum matching is maximal, but not conversely: in path a−b−c−da - b - c - d, matching {bc}\{bc\} is maximal (every other edge touches bb or cc) but not maximum, because {ab,cd}\{ab, cd\} has two edges. The greedy strategy, adding edges while possible, produces maximal matchings and can get stuck at half the optimal size.

The way out is the central observation of matching theory. In the example, path a−b−c−da - b - c - d starts and ends at free vertices and alternates edges outside and inside MM: outside (abab), inside (bcbc), outside (cdcd). Swap the roles of its edges: those inside leave, those outside enter, and the matching grows by one edge.

Check that M△PM \triangle P remains a matching vertex by vertex: interior path vertices change partners but retain exactly one, endpoints change from free to saturated, and the rest are untouched. Surprisingly, this local operation suffices to reach the optimum.

Proof

If there is an augmenting path PP, M△PM \triangle P is larger, so MM is not maximum. Conversely, suppose MM is not maximum and let M′M' with ∣M′∣>∣M∣|M'| > |M|. In graph HH with edges M△M′M \triangle M' every vertex has degree at most 2 (one edge from each matching), so its components are paths and cycles, and in all of them edges alternate between MM and M′M'. Alternating cycles have even length and as many edges from MM as from M′M'. Since HH has more edges of M′M' than of MM in total, some component is a path with one more edge of M′M' than of MM: it begins and ends with edges of M′M', and its endpoints are free in MM, because if one were saturated by MM that edge of MM would be in HH and extend the path. It is an augmenting path for MM.

∎

Berge immediately gives an algorithm: start with M=∅M = \varnothing and, while an augmenting path exists, flip it. Each step increases ∣M∣|M| by one, so there are at most ∣V∣/2|V|/2 steps. The difficulty is finding paths. In a bipartite graph, alternating breadth-first search suffices: from a free vertex of XX follow edges outside MM to YY, and from YY return to XX along its unique edge of MM, if any. In general graphs, odd cycles confuse the search and Edmonds’s blossom algorithm is needed, covered in algorithms.

Hall’s theorem: a certificate for no

Return to the GPUs. Call the jobs XX and the GPUs YY, and join each job to the GPUs it fits: a bipartite graph. We want a matching that saturates XX. There is an obvious obstruction: if three jobs collectively fit only two GPUs, one is left out. In general, if a set S⊆XS \subseteq X has fewer neighbors than elements, ∣N(S)∣<∣S∣|N(S)| < |S|, there is no assignment. Hall’s theorem says this is the only possible obstruction.

The condition on the right is Hall’s condition, and an SS violating it is a violating set. The forward implication is the obvious obstruction: if MM saturates XX, the vertices of SS have distinct partners, all in N(S)N(S). The converse is the real content, and our proof is an algorithm: it either finds the matching or constructs a violating set.

Proof

Assume Hall’s condition and let MM be a maximum matching. If it saturates XX, we are done. Otherwise let x∈Xx \in X be free, and let ZZ be the set of vertices reachable from xx by alternating paths (starting with an edge outside MM), including xx itself. Write S=X∩ZS = X \cap Z and T=Y∩ZT = Y \cap Z.

  1. Every y∈Ty \in T is saturated, and its partner lies in SS. If yy were free, the alternating path from xx to yy would be augmenting, and MM would not be maximum (Berge). Its partner is reached by extending the path along the edge of MM.
  2. Every s∈Ss \in S other than xx is the partner of some y∈Ty \in T. Alternating paths from xx always reach XX along an edge of MM.
  3. N(S)=TN(S) = T. If s∈Ss \in S and y∈N(s)y \in N(s): either sy∈Msy \in M, and then yy is the edge used to reach ss, or sy∉Msy \notin M, and extending the path from xx to ss with sysy gives an alternating path to yy. In both cases y∈Zy \in Z.

By 1 and 2, MM matches TT to S∖{x}S \setminus \{x\}, so ∣N(S)∣=∣T∣=∣S∣−1<∣S∣|N(S)| = |T| = |S| - 1 < |S|, contrary to Hall’s condition.

∎

Read the proof backwards for an algorithm with a certificate: launch alternating search from each free candidate; if it reaches a free position, flip the path; otherwise the candidates reached form a violating set with exactly one fewer neighbor than elements. Try it.

InteractiveMatching or violating set
Candidates XPositions YABCDEF123456
From F, the search (purple) finds augmenting path F - 1 - A - 2 - B - 3 - C - 4 - D - 5 - E - 6: it alternates edges outside and inside MM and both endpoints are free.
12 / 14
  • matching MM
  • augmenting path
  • alternating search
  • SS and its edges
  • N(S)N(S)
∣M∣|M|, matching size5 of 6
Candidates on the left, positions on the right. Play the algorithm: each free candidate launches an alternating search (purple); if it reaches a free position, the augmenting path (magenta) is flipped. The initial example opens at the key moment: F knows only position 1, and placing F forces all others to move. In ‘Bottleneck’ (Cuello de botella), the search gets stuck and marks a set SS (red) with fewer positions in N(S)N(S) (orange) than candidates. Edit the graph by clicking a candidate and then a position, and enable König's cover at the end.

What you should have seen:

  • An augmenting path can be long. In the initial example, F knows only position 1, occupied by A; A can move to 2, occupied by B; and so on to E, for whom 6 is free. Path F−1−A−2−⋯−E−6F - 1 - A - 2 - \cdots - E - 6 has 11 edges and flipping it moves all candidates without any losing a position. A greedy assignment would never find it.
  • The dead end leaves a verifiable trace. In the bottleneck, A, C, and E know only positions 2 and 5. The search from the candidate left out reaches exactly S={A,C,E}S = \{A, C, E\} and N(S)={2,5}N(S) = \{2, 5\}. To convince someone there is no assignment, there is no need to show the algorithm: point to those three candidates and two positions.
  • The violator’s deficit is what is missing. With “Six for five positions,” the final violator satisfies ∣S∣−∣N(S)∣=∣X∣−∣M∣|S| - |N(S)| = |X| - |M|: it not only proves there is no perfect matching, but that the one found is the best possible.

The last observation is worth stating as a theorem, because this is how Hall is used in practice: the worst bottleneck fixes the size of the best matching.

Proof

Any matching leaves at least ∣S∣−∣N(S)∣|S| - |N(S)| vertices of each SS free, because those of SS can only occupy positions in N(S)N(S): this gives ≤\le. For equality, take a maximum MM and launch alternating search from all free vertices of XX at once. The same reasoning as in Hall’s proof shows that the reached vertices, S=X∩ZS = X \cap Z, satisfy N(S)=Y∩ZN(S) = Y \cap Z, that MM matches Y∩ZY \cap Z to the saturated vertices of SS, and that all free vertices of XX lie in SS. Thus ∣S∣−∣N(S)∣|S| - |N(S)| is exactly the number of free vertices of XX, namely ∣X∣−∣M∣|X| - |M|.

∎

A classical consequence, proved by double counting: every kk-regular bipartite graph with k≥1k \ge 1 has a perfect matching. The edges leaving SS number k∣S∣k|S| and all reach N(S)N(S), which receives k∣N(S)∣k|N(S)| edges total; hence k∣S∣≤k∣N(S)∣k|S| \le k|N(S)| and Hall holds. Also k∣X∣=∣E∣=k∣Y∣k|X| = |E| = k|Y|, so saturating XX saturates everything. Removing that matching leaves an (k−1)(k-1)-regular graph, and repeating partitions edges into kk perfect matchings. This underlies league schedules: over kk rounds, each team in one group plays each of the kk in the other once.

The Hall proof you saw constructs the matching. The classical proof by strong induction, due to Halmos and Vaughan (1950), is shorter and gives no algorithm; complete it yourself.

ProofHall by induction on |X|
Prove: If GG is bipartite with parts XX and YY and ∣N(S)∣≥∣S∣|N(S)| \ge |S| for every S⊆XS \subseteq X, there is a matching saturating XX.
0
Use strong induction on ∣X∣|X|. With ∣X∣=1|X| = 1 the claim is immediate: the only candidate has a neighbor. Suppose ∣X∣≥2|X| \ge 2 and the result holds for every bipartite graph with fewer candidates satisfying Hall's condition.

Step 1 of 4. Which division into cases advances the induction?

König’s theorem: a minimum equals a maximum

Hall’s certificate answers “can XX be saturated?” If the answer is no, how do you certify that a particular matching is the largest possible? A different kind of object is needed, one bounding all matchings from above at once.

In any graph, ν(G)≤τ(G)\nu(G) \le \tau(G): matching edges share no endpoints, so a cover needs a distinct vertex for each. This is weak duality, and it suffices to certify optimality: if you find a matching and a cover of the same size, both are optimal. In a triangle this is impossible: ν=1\nu = 1 and τ=2\tau = 2. In bipartite graphs it is always possible.

This is König’s theorem, and its proof reuses alternating search: the same set ZZ that gave Hall’s violator gives the cover.

Proof

Let MM be a maximum matching and ZZ the set of vertices reachable by alternating paths from free vertices of XX (including those vertices). Take

C=(X∖Z)∪(Y∩Z).C = (X \setminus Z) \cup (Y \cap Z).

CC is a cover. Let xyxy be an edge, with x∈Xx \in X. If x∉Zx \notin Z, then x∈Cx \in C. If x∈Zx \in Z, yy is reached from xx: along edge xyxy if it is not in MM, and if it is in MM it is the edge used to reach xx (a saturated xx of ZZ is only reached through its partner). In both cases y∈Zy \in Z, hence y∈Cy \in C.

∣C∣≤∣M∣|C| \le |M|. Every vertex of CC is saturated: free vertices of XX lie in ZZ, so not in X∖ZX \setminus Z; and a free y∈Y∩Zy \in Y \cap Z would give an augmenting path, impossible by Berge. Moreover, no edge of MM has both endpoints in CC: if xy∈Mxy \in M with y∈Zy \in Z, extending the path along xyxy gives x∈Zx \in Z, hence x∉Cx \notin C. Thus each vertex of CC belongs to a different edge of MM, and ∣C∣≤∣M∣|C| \le |M|.

By weak duality, ∣M∣≤τ(G)≤∣C∣≤∣M∣|M| \le \tau(G) \le |C| \le |M|, and all inequalities are equalities.

∎

Enable König’s cover in the first interactive: the green marks are CC, there are as many as edges in MM, and each lies on a different matching edge. This optimality certificate can be checked in seconds.

Hall follows from König in two lines, showing the two theorems express the same phenomenon: if Hall’s condition holds and CC is a cover, vertices of X∖CX \setminus C have all their neighbors in C∩YC \cap Y, so ∣C∩Y∣≥∣N(X∖C)∣≥∣X∖C∣|C \cap Y| \ge |N(X \setminus C)| \ge |X \setminus C| and ∣C∣≥∣X∣|C| \ge |X|. Thus ν=τ≥∣X∣\nu = \tau \ge |X|.

Coloring and chromatic number

This is coloring, a pure constraint satisfaction problem: one variable per vertex, a domain of kk values, and a “different” constraint per edge. Lower bounds come from substructures forcing colors to be used:

  • Cliques. If GG contains a KrK_r, its rr vertices need different colors: χ(G)≥ω(G)\chi(G) \ge \omega(G), the largest clique size.
  • Independent sets. Each color class has at most α(G)\alpha(G) vertices, so χ(G)≥∣V∣/α(G)\chi(G) \ge |V| / \alpha(G).
  • Odd cycles. χ(G)≤2\chi(G) \le 2 if and only if GG is bipartite, that is, if and only if it has no odd cycles. An odd cycle forces 3 colors.

Greedy coloring and order

The most natural algorithm visits vertices in an order v1,…,vnv_1, \dots, v_n and gives each the smallest color unused by any already colored neighbor.

Proof
  1. When viv_i arrives, its colored neighbors block at most d−(vi)d^-(v_i) colors, so one of {1,…,d−(vi)+1}\{1, \dots, d^-(v_i) + 1\} is free.
  2. Take an optimal coloring cc and order vertices by class: color 1 first, then color 2, and so on. By strong induction on position, greedy gives each vertex vv a color ≤c(v)\le c(v). A neighbor ww preceding vv has c(w)≤c(v)c(w) \le c(v) by the order, and c(w)≠c(v)c(w) \ne c(v) because classes are independent; hence c(w)<c(v)c(w) < c(v) and, by induction, its greedy color is ≤c(w)<c(v)\le c(w) < c(v). No earlier neighbor has color c(v)c(v), so vv receives a color ≤c(v)\le c(v). The total is ≤max⁡c=χ(G)\le \max c = \chi(G), and it cannot be smaller.
∎

The second part is a warning disguised as good news: coloring is exactly the problem of finding a good order, and that is as hard as coloring. With a bad order, greedy can be catastrophic even on the easiest graph, a bipartite one.

InteractiveOrder matters in greedy coloring
1u12u23u34u45u51v12v23v34v45v5
Coloring order (left to right)
Step 10: v5v_{5}. Its colored neighbors use 1, 2, 3, 4, so it receives 5, the smallest available color.
10 / 10
Graph
5
Colors with this order5
DSatur2
χ(G)\chi(G) (exact)2
ω(G)\omega(G), maximum clique2
Bound 1+max⁡1 + \max previous neighbors5
Bound Δ+1\Delta + 15
This order uses 3 extra colors. The graph is bipartite: two colors suffice.
The crown graph has vertices u1,…,unu_1, \dots, u_n and v1,…,vnv_1, \dots, v_n, with uiu_i joined to vjv_j whenever i≠ji \ne j: it is Kn,nK_{n,n} minus a perfect matching and is therefore bipartite. In order u1,v1,u2,v2,…u_1, v_1, u_2, v_2, \dots greedy uses nn colors; with ‘one side, then the other’, 2. Play coloring step by step and notice which colors already colored neighbors block. Click two vertices to swap their order and find an optimal order, compare with DSatur, and switch to Petersen and Grötzsch.

What you should have seen:

  • On the crown, alternating order is a perfect trap. u1u_1 and v1v_1 are not neighbors and receive color 1. u2u_2 neighbors v1v_1, so receives 2, and v2v_2, a neighbor of u1u_1, also gets 2. On reaching uku_k, its neighbors v1,…,vk−1v_1, \dots, v_{k-1} already use colors 1,…,k−11, \dots, k-1, so it needs kk. Result: nn colors for a graph colorable with 2. Ordering by degree does not help because all vertices have degree n−1n - 1.
  • The order bound is tight for alternating order, and only a bound for the other. In alternating order, uku_k and vkv_k have k−1k - 1 earlier neighbors, so 1+max⁡d−=n1 + \max d^- = n, exactly the colors used. In side-by-side order the bound remains nn because each vjv_j has n−1n - 1 earlier neighbors, but all have the same color and greedy uses 2.
  • DSatur succeeds. It first colors the vertex with the most distinct colors among its neighbors (most saturated), breaking ties by degree. On the crown it finds 2 colors at any size.
  • Petersen and Grötzsch are triangle-free yet need 3 and 4 colors. ω=2\omega = 2 for both: the clique bound can miss by a lot.

DSatur, due to Brélaz (1979), optimally colors every bipartite graph, but is not optimal in general. For the bipartite case: while an already started component has an uncolored vertex, DSatur picks one with saturation at least 1, i.e. adjacent to a colored vertex; in a bipartite graph all its colored neighbors lie on the other side and, by induction, have the same color, so it receives the other of the two. Another heuristic with a guarantee is smallest-last order: repeatedly remove a minimum-degree vertex and color in reverse order. If every subgraph of GG has a vertex of degree ≤d\le d (GG is called dd-degenerate), each vertex has at most dd earlier neighbors and greedy uses at most d+1d + 1 colors. You will use this shortly for planar graphs.

Bounds, Brooks, and the gap between ω and χ

The bound Δ+1\Delta + 1 is attained by complete graphs (KnK_n has Δ=n−1\Delta = n - 1 and χ=n\chi = n) and odd cycles (Δ=2\Delta = 2, χ=3\chi = 3). Brooks’s theorem (1941), stated without proof, says these are the only cases.

In the other direction, bound χ≥ω\chi \ge \omega can be arbitrarily poor. Mycielski’s construction takes a triangle-free graph of chromatic number kk and produces another triangle-free graph of chromatic number k+1k + 1: from an edge it produces cycle C5C_5 (χ=3\chi = 3) and from C5C_5 the Grötzsch graph (χ=4\chi = 4) in the interactive. Triangle-free graphs exist requiring arbitrarily many colors. Chromatic number is not a local property.

Planar graphs

Planarity is a property of the graph; crossings are a property of a drawing. The same K4K_4 can be drawn as a square with two crossing diagonals, or as a triangle with a vertex in the center and no crossings. To prove a graph is not planar, all infinitely many possible drawings must be ruled out. Fáry’s theorem (1948) at least allows restriction to straight-line drawings: every simple planar graph has a straight-line plane drawing. But even then not all can be tried. An invariant is needed.

Euler’s formula

Proof

Use induction on EE, with VV fixed. If GG is a tree, E=V−1E = V - 1 by the tree characterization, and its drawing has one face because it encloses no region: V−(V−1)+1=2V - (V - 1) + 1 = 2. Otherwise it has a cycle CC. By the Jordan curve theorem, CC separates the plane into an interior and exterior, so an edge ee of CC has a distinct interior face on one side and exterior face on the other. Removing ee merges those faces, and G−eG - e remains connected because ee was on a cycle. By induction, V−(E−1)+(F−1)=2V - (E - 1) + (F - 1) = 2, which is the same as V−E+F=2V - E + F = 2.

With cc components, add c−1c - 1 edges one at a time, each between distinct components sharing a face (while the graph is disconnected, some face touches two components), drawn within that face: each increases EE by one without changing FF, because it joins two distinct boundary pieces and encloses no region, and the resulting graph is connected, so V−(E+c−1)+F=2V - (E + c - 1) + F = 2.

∎

The formula is surprising at first: the number of faces does not depend on the drawing. Two very different plane drawings of the same connected graph have exactly the same number of faces, 2−V+E2 - V + E. This rigidity allows impossibility proofs.

Counting faces to prove impossibility

The idea is double counting pairs (edge, side of edge). Define the degree of a face as the number of edges on its boundary, counting an edge twice if the same face lies on both sides. Each edge has two sides, so the sum of face degrees is 2E2E. If every face has degree at least 3, then 2E≥3F2E \ge 3F, and Euler gives a bound that does not mention the drawing.

ProofThe 3V − 6 bound and nonplanarity of K5
Prove: Every simple planar graph with V≥3V \ge 3 vertices satisfies E≤3V−6E \le 3V - 6. Consequently, K5K_5 is nonplanar.
0
It suffices to prove this for connected graphs: adding edges between components through the outer face preserves planarity and only increases EE. Take a plane drawing with FF faces. Being connected with V≥3V \ge 3, it has at least two edges.

Step 1 of 4. What is the sum of all face degrees?

The argument generalizes using girth gg, the shortest cycle’s length. In a connected plane graph that is not a tree, every face boundary contains a cycle, so each face has degree at least gg: 2E≥gF=g(2−V+E)2E \ge gF = g(2 - V + E), that is,

E≤gg−2 (V−2).E \le \frac{g}{g - 2}\,(V - 2).

With g=3g = 3 this is 3V−63V - 6; with g=4g = 4, 2V−42V - 4; and the Petersen graph, with V=10V = 10, E=15E = 15, and g=5g = 5, violates it: 15>53⋅8≈13.315 > \tfrac53 \cdot 8 \approx 13.3. Try it by hand before believing it.

InteractiveUntangle or prove it impossible
  • uncrossed edge
  • crossed edge
Crossings in this drawing33
VV, EE9, 16
Girth gg (shortest cycle)3
Bound E≤3V−6E \le 3V - 616 ≤ 21
The bound does not rule it out. Keep untangling: this graph does admit a planar drawing.
Drag vertices until no edges cross: red edges cross another edge. You can do this for planar graphs, and then the panel counts the drawing's faces FF and checks V−E+F=2V - E + F = 2. For K5K_5, K3,3K_{3,3}, and Petersen, the panel compares EE with the girth bound: if it exceeds the bound, no drawing can be crossing-free. ‘View minimum crossings’ (Ver el mínimo de cruces) shows the best possible. Finish with ‘K3,3 plus an edge’, which satisfies the bound but is still nonplanar, and enable Kuratowski highlighting.

What you should have seen:

  • Faces do not depend on the drawing. Untangle the octahedron in two different ways: there are always 8 faces, 2−6+122 - 6 + 12.
  • For K5K_5 and K3,3K_{3,3} one crossing remains, and this is not lack of skill. 10>910 > 9 and 9>89 > 8 completely prove no plane drawing exists. Their minimum crossing numbers are both 1, and Petersen’s is 2.
  • The bound is necessary, not sufficient. K3,3K_{3,3} plus an edge has triangles, so its bound is 3V−6=12≥103V - 6 = 12 \ge 10, yet it contains a K3,3K_{3,3}, which cannot be drawn without crossings. EE satisfying the bound proves nothing.
  • Petersen’s highlighting is not a literal K3,3K_{3,3}. It is a subdivision: a K3,3K_{3,3} in which some edges have been replaced by paths (the small vertices). Subdivision does not change planarity.

The last point shows the complete characterization of planarity, one of the great theorems of graph theory.

You just proved the easy direction: K5K_5 and K3,3K_{3,3} are nonplanar, and subdividing or adding edges does not fix this. We do not prove the hard direction, that every nonplanar graph contains one of those obstructions. Wagner (1937) gave an equivalent version using minors, which also allow edge contraction: a graph is planar if and only if it has neither K5K_5 nor K3,3K_{3,3} as a minor. For us, the key point is that planarity has certificates in both directions: a plane drawing for yes, a Kuratowski subdivision for no. The planarity test has been linear since Hopcroft and Tarjan (1974), and modern algorithms produce the appropriate certificate in linear time; networkx.check_planarity returns one or the other.

Five colors suffice

With E≤3V−6E \le 3V - 6, the degree sum is 2E≤6V−12<6V2E \le 6V - 12 < 6V, so the average degree of a simple planar graph is less than 6: every planar graph has a vertex of degree at most 5. Since subgraphs of a planar graph are planar, every planar graph is 5-degenerate, and smallest-last order colors it with 6 colors. Write this as induction:

ProofEvery planar graph is 6-colorable
Prove: Every simple planar graph is 6-colorable.
0
Use induction on VV. If V≤6V \le 6, one color per vertex suffices. Suppose V≥7V \ge 7 and the result holds for planar graphs with fewer vertices.

Step 1 of 3. Which vertex do you choose?

Reaching five colors requires a new idea, Kempe chains, and the proof is beautiful.

Proof

Use induction on VV, as before: take a plane drawing, a vertex vv of degree ≤5\le 5, and a 5-coloring of G−vG - v. If the neighbors of vv use at most 4 colors, one is free. Otherwise vv has exactly 5 neighbors v1,…,v5v_1, \dots, v_5, in their order around vv in the drawing, with colors 1,…,51, \dots, 5.

Call H13H_{13} the subgraph induced by vertices of colors 1 and 3. If v1v_1 and v3v_3 are in different components of H13H_{13}, swap colors 1 and 3 in the component of v1v_1. The coloring remains proper: an edge between a vertex in the component and one outside cannot join two colors of {1,3}\{1, 3\}, because the outside vertex would then be in the component. Now v1v_1 has color 3, v3v_3 keeps its color, and 1 is free for vv.

If v1v_1 and v3v_3 are in the same component, there is a path from v1v_1 to v3v_3 alternating colors 1 and 3, which with vv forms a cycle CC. Since v2v_2 and v4v_4 lie between v1v_1 and v3v_3 on opposite sides in the circular order around vv, CC leaves one inside and the other outside (Jordan curve). Any path from v2v_2 to v4v_4 in the plane drawing crosses CC at a vertex, and all vertices of CC have color 1 or 3, or are vv, which is uncolored. Thus v2v_2 and v4v_4 lie in different components of H24H_{24}, and swapping 2 and 4 in the component of v2v_2 frees color 2 for vv.

∎

In 1879 Kempe published a four-color “proof” using exactly this technique. The hard case required two swaps at once, and Heawood discovered in 1890 that they can interfere; in pointing out the error, he salvaged the five-color argument.

The four-color theorem and computer-assisted proof

The four-color statement, conjectured by Francis Guthrie in 1852 while coloring a map of English counties, says every planar graph is 4-colorable. (A map becomes a graph by placing a vertex in each country and an edge between countries sharing a border; the resulting graph is planar.) Four cannot be lowered: K4K_4 is planar and needs four.

Kenneth Appel and Wolfgang Haken’s proof (1976) follows the five-color proof’s structure, but on an industrial scale. It has two parts:

  • Unavoidability. A finite set of configurations (small subgraphs with their degrees) such that every triangulated planar graph contains at least one. A “discharging” argument proves it: assign charge 6−deg⁡v6 - \deg v to each vertex, which by Euler sums to 12>012 > 0, and redistribution rules force some configuration in the set to appear.
  • Reducibility. Each configuration is reducible: if a minimal counterexample contained it, it could be colored, using elaborate Kempe-style arguments. For almost two thousand configurations, a computer performed this check, with more than a thousand hours of computation.

The mathematical community was divided. Is a proof no human can read in full a proof? In 1996 Robertson, Sanders, Seymour, and Thomas gave a simpler version with 633 configurations and 32 discharging rules, and programs anyone could rerun. But the underlying question remained: who verifies the program?

The answer came in 2005, when Georges Gonthier and Benjamin Werner formalized the complete proof in the Coq proof assistant. One need no longer trust the configuration-checking program, only Coq’s kernel, a small program verifying every logical step; even the topological part (what a plane map is, the Jordan curve) is formalized combinatorially. This example opened the door to modern assisted proof, revisited at the end of the module with Lean and language models that write proofs.

Ramsey theory

In the counting lesson you proved with the pigeonhole principle that every two-coloring of the edges of K6K_6 has a monochromatic triangle, and K5K_5 does not suffice. This is the first case of a general phenomenon: total disorder is impossible, and every sufficiently large structure contains an ordered piece.

The existence of NN is not obvious and must be proved first. The trivial cases are R(s,2)=sR(s, 2) = s and R(2,t)=tR(2, t) = t: a coloring of KsK_s without a red KsK_s has some blue edge, a blue K2K_2, and all-red Ks−1K_{s-1} has neither, so s−1s - 1 vertices do not suffice. You already know R(3,3)=6R(3, 3) = 6.

The upper bound: the pigeonhole principle again

Proof

Let a=R(s−1,t)a = R(s - 1, t) and b=R(s,t−1)b = R(s, t - 1), which exist by induction on s+ts + t, and color Ka+bK_{a+b}. A vertex vv has a+b−1a + b - 1 edges, so by the pigeonhole principle it has at least aa red or at least bb blue edges (otherwise it would have at most (a−1)+(b−1)(a - 1) + (b - 1)).

If it has at least aa red neighbors, among them there is, by definition of aa, a red Ks−1K_{s-1}, which with vv forms a red KsK_s, or a blue KtK_t. The other case is symmetric. Thus R(s,t)≤a+bR(s, t) \le a + b.

For the closed form, use induction on s+ts + t with Pascal’s rule: (s+t−3s−2)+(s+t−3s−1)=(s+t−2s−1)\binom{s+t-3}{s-2} + \binom{s+t-3}{s-1} = \binom{s+t-2}{s-1}, and in the base cases (t1)=t\binom{t}{1} = t and (ss−1)=s\binom{s}{s-1} = s.

∎

With s=t=ks = t = k and the binomial theorem, R(k,k)≤(2k−2k−1)<4k−1R(k, k) \le \binom{2k-2}{k-1} < 4^{k-1}. For k=3k = 3 the bound gives exactly 6. For k=4k = 4 it gives 20, while the actual value is R(4,4)=18R(4, 4) = 18. Beyond that little is known: 43≤R(5,5)≤4643 \le R(5, 5) \le 46, and in 2023 Campos, Griffiths, Morris, and Sahasrabudhe proved R(k,k)≤(4−ε)kR(k, k) \le (4 - \eps)^k for a fixed ε>0\eps > 0, the first exponential improvement to the 1935 bound.

The lower bound: the probabilistic method

To prove R(k,k)>nR(k, k) > n one must exhibit a coloring of KnK_n without a monochromatic KkK_k. For large kk nobody knows how to construct a good one. Erdős observed in 1947 that this is unnecessary: it suffices to prove that a random coloring works with positive probability.

Proof

Color each edge of KnK_n red or blue with probability 12\tfrac12, independently. For each set AA of kk vertices, let IAI_A indicate that its (k2)\binom{k}{2} edges have the same color: there are two monochromatic colorings of those edges among 2(k2)2^{\binom{k}{2}}, so P(IA=1)=21−(k2)\Pr(I_A = 1) = 2^{1 - \binom{k}{2}}. The number of monochromatic KkK_k is X=∑AIAX = \sum_A I_A and, by linearity of expectation,

E[X]=(nk) 21−(k2).\E[X] = \binom{n}{k}\, 2^{1 - \binom{k}{2}}.

If E[X]<1\E[X] < 1, it cannot be that X≥1X \ge 1 for every coloring, because then the mean would be at least 1. Thus some coloring has X=0X = 0, and R(k,k)>nR(k, k) > n. (This is the union bound: P(X≥1)≤∑AP(IA=1)=E[X]\Pr(X \ge 1) \le \sum_A \Pr(I_A = 1) = \E[X].)

∎

The explicit bound is an exponent calculation. Take n=⌊2k/2⌋n = \lfloor 2^{k/2} \rfloor and follow the steps:

(nk)≤nkk!\binom{n}{k} \le \frac{n^k}{k!}
The product n(n−1)⋯(n−k+1)n(n-1)\cdots(n-k+1) has kk factors, all ≤n\le n.
1/4

The bound 2k/22^{k/2} is generous; the exact condition E[X]<1\E[X] < 1 gives more. For k=4k = 4 it works up to n=6n = 6 ((64)⋅2−5≈0.47\binom{6}{4} \cdot 2^{-5} \approx 0.47), and for k=10k = 10 up to n=100n = 100, versus 25=322^5 = 32. Check how it behaves on actual colorings.

InteractiveRandom colorings avoiding cliques
012345
No monochromatic K4K_4 in this coloring.
Distribution of XX in 500 random colorings
X = 0: 341 coloringsX = 1: 97 coloringsX = 2: 51 coloringsX = 3: 7 coloringsX = 4: 1 coloringsX = 5: 3 coloringsE[X] = 0.4705
  • red edge
  • blue edge
  • colorings with X=0X = 0
  • theoretical E[X]\E[X]
Target clique KkK_k
6
XX in this coloring0
E[X]=(64) 21−6\E[X] = \binom{6}{4}\, 2^{1 - 6}0.469
Mean XX across 500 colorings0.478
Fraction with X=0X = 068.2 %
Bound P(X=0)≥1−E[X]\Pr(X = 0) \ge 1 - \E[X]53.1 %
Erdős threshold for k=4k = 4R(4, 4) > 6
E[X]<1\E[X] < 1, so some coloring has X=0X = 0 (if all had X≥1X \ge 1, the mean would be ≥1\ge 1). Thus R(4,4)>6R(4, 4) > 6, without constructing one.
Each edge of KnK_n is randomly colored red or blue. XX counts monochromatic KkK_k subgraphs, and one is highlighted if it exists. The histogram collects 500 colorings: the green bar counts those with none. Change nn and compare the green fraction with expected value E[X]\E[X] (dashed line): when E[X]<1\E[X] < 1, the bound P(X=0)≥1−E[X]\Pr(X = 0) \ge 1 - \E[X] guarantees some exist. With k=4k = 4 and n=17n = 17, try the Paley coloring.

What you should have seen:

  • Below the threshold, good colorings are the majority. With k=4k = 4 and n=6n = 6, E[X]≈0.47\E[X] \approx 0.47, and around 70% of colorings have no monochromatic K4K_4, above the guarantee 1−E[X]≈53%1 - \E[X] \approx 53\%. The union bound is pessimistic because it counts colorings with multiple cliques more than once.
  • Above it, they become rare but not impossible. With n=7n = 7, E[X]≈1.09\E[X] \approx 1.09 and the argument no longer guarantees anything; still, more than 40% of colorings are good. The method gives a bound, not the exact value.
  • Randomness falls far short. With n=17n = 17, E[X]≈74\E[X] \approx 74 and practically no random coloring avoids the K4K_4. But one exists, Paley’s: edge ijij is red if j−ij - i is a square modulo 17. Try R(4,4)>17R(4, 4) > 17, which with the recurrence R(4,4)≤R(3,4)+R(4,3)=9+9=18R(4, 4) \le R(3, 4) + R(4, 3) = 9 + 9 = 18 gives the exact value.

The probabilistic method proves a good coloring exists without saying which. For large kk this remains true: almost all colorings of KnK_n with n=2k/2n = 2^{k/2} are good, yet no explicit construction is known achieving an exponential bound ckc^k with c>1c > 1. The gap between 2 k\sqrt{2}^{\,k} and 4k4^k remains open more than seventy years later: the lower bound has improved only by a constant factor (Spencer, 1975, asymptotically doubled Erdős’s using the Lovász local lemma), and the upper bound’s exponential base from 4 to 4−ε4 - \eps.

Implementation from scratch: verifiable certificates

Implement each result in the lesson to return its certificate, and write an independent verifier that checks it without trusting the algorithm. This is the right way to test combinatorial optimization code: the algorithm may be intricate, but the verifier is simple enough to inspect.

The central piece is alternating search. It receives roots (free vertices of XX) and returns the first free position found with parents to reconstruct the path, or None with everything reached. flip flips the augmenting path, and hall_or_violator turns the proof of Hall’s theorem into code.

[ ]Matching or violating set, with verifierBrowser
from collections import deque
import random, itertools

def alternating_search(adj, roots, match_x, match_y):
    """BFS alternante desde roots (en X): fuera de M hacia Y, por M de vuelta a X.
    Devuelve (y libre o None, parent: y -> x desde el que se alcanzó, X alcanzados)."""
    parent, seen_x = {}, set(roots)
    queue = deque(roots)
    while queue:
        x = queue.popleft()
        for y in adj[x]:
            if y in parent:
                continue
            parent[y] = x
            if y not in match_y:
                return y, parent, seen_x
            x2 = match_y[y]                      # se vuelve a X por la arista de M
            if x2 not in seen_x:
                seen_x.add(x2)
                queue.append(x2)
    return None, parent, seen_x

def flip(y, parent, match_x, match_y):
    """Invierte el camino aumentante que termina en el puesto libre y."""
    while True:
        x = parent[y]
        prev = match_x.get(x)                    # el puesto que x deja libre
        match_x[x], match_y[y] = y, x
        if prev is None:                         # x era la raíz, libre
            return
        y = prev

def hall_or_violator(adj, X):
    """('emparejamiento', M) con M: x -> y que satura X, o ('violador', S) con |N(S)| < |S|."""
    match_x, match_y = {}, {}
    for root in X:
        y, parent, seen_x = alternating_search(adj, [root], match_x, match_y)
        if y is None:
            return "violador", seen_x            # N(S) = Y alcanzados, emparejados con S − {root}
        flip(y, parent, match_x, match_y)
    return "emparejamiento", match_x

def N(adj, S):
    return set().union(*(adj[x] for x in S)) if S else set()

def verify(adj, X, kind, cert):
    """Verificador independiente: no usa nada del algoritmo."""
    if kind == "emparejamiento":
        ys = list(cert.values())
        return set(cert) == set(X) and len(set(ys)) == len(ys) and all(cert[x] in adj[x] for x in X)
    S = set(cert)
    return bool(S) and S <= set(X) and len(N(adj, S)) < len(S)

cadena = {"A": [1, 2], "B": [2, 3], "C": [3, 4], "D": [4, 5], "E": [5, 6], "F": [1]}
cuello = {"A": [2, 5], "B": [1, 2, 3], "C": [2, 5], "D": [3, 4, 6], "E": [2, 5], "F": [1, 4, 6]}
for nombre, adj in [("cadena", cadena), ("cuello de botella", cuello)]:
    kind, cert = hall_or_violator(adj, list(adj))
    detalle = cert if kind == "emparejamiento" else f"S = {sorted(cert)}, N(S) = {sorted(N(adj, cert))}"
    print(f"{nombre:18s} {kind}: {detalle}   verificado: {verify(adj, list(adj), kind, cert)}")

rng = random.Random(0)
validos = acuerdo = 0
for _ in range(3000):
    X = list(range(6))
    adj = {x: sorted(rng.sample(range(6), rng.randint(0, 3))) for x in X}
    kind, cert = hall_or_violator(adj, X)
    validos += verify(adj, X, kind, cert)
    hall = all(len(N(adj, S)) >= len(S) for r in range(1, 7) for S in itertools.combinations(X, r))
    acuerdo += (kind == "emparejamiento") == hall
print(f"3000 grafos al azar: certificados válidos {validos}; coincide con la condición de Hall por fuerza bruta: {acuerdo}")

The maximum matching and König cover come from the same two functions. On thousands of random bipartite graphs with sides of different sizes, check the three claims in the König section: that CC is a cover, that ∣C∣=∣M∣|C| = |M|, and that the final violator has deficiency ∣X∣−∣M∣|X| - |M|. Then use brute force on small nonbipartite graphs.

[ ]König: the cover certifying the maximumBrowser
def maximum_matching(adj, X):
    match_x, match_y = {}, {}
    for root in X:
        y, parent, _ = alternating_search(adj, [root], match_x, match_y)
        if y is not None:
            flip(y, parent, match_x, match_y)
    return match_x, match_y

def konig(adj, X):
    """Emparejamiento máximo M, cubrimiento C = (X − Z) ∪ (Y ∩ Z) y violador S = X ∩ Z."""
    match_x, match_y = maximum_matching(adj, X)
    libres = [x for x in X if x not in match_x]
    y, parent, ZX = alternating_search(adj, libres, match_x, match_y)
    assert y is None, "quedaba un camino aumentante: M no era máximo"
    C = {("x", x) for x in set(X) - ZX} | {("y", y) for y in parent}
    return match_x, C, ZX

def is_cover(adj, C):
    return all(("x", x) in C or ("y", y) in C for x in adj for y in adj[x])

ok = 0
for _ in range(3000):
    nx_, ny_ = rng.randint(1, 8), rng.randint(1, 8)
    X = list(range(nx_))
    adj = {x: sorted(rng.sample(range(ny_), rng.randint(0, min(3, ny_)))) for x in X}
    M, C, S = konig(adj, X)
    ok += is_cover(adj, C) and len(C) == len(M) and len(S) - len(N(adj, S)) == len(X) - len(M)
print(f"König en 3000 bipartitos al azar: {ok} certificados correctos")
M, C, S = konig(cuello, list(cuello))
print("cuello de botella: |M| =", len(M), " C =", sorted(C), " S =", sorted(S))

def nu_tau(n, edges):
    """Fuerza bruta: emparejamiento máximo y cubrimiento mínimo de un grafo cualquiera."""
    nu = max(r for r in range(len(edges) + 1) for F in itertools.combinations(edges, r)
             if len({v for e in F for v in e}) == 2 * r)
    tau = min(r for r in range(n + 1) for C in itertools.combinations(range(n), r)
              if all(u in C or v in C for u, v in edges))
    return nu, tau
for nombre, n, E in [("triángulo", 3, [(0, 1), (1, 2), (0, 2)]), ("C5", 5, [(i, (i + 1) % 5) for i in range(5)]),
                     ("C6", 6, [(i, (i + 1) % 6) for i in range(6)]), ("K4", 4, list(itertools.combinations(range(4), 2)))]:
    nu, tau = nu_tau(n, E)
    print(f"{nombre:10s} ν = {nu}, τ = {tau}  {'(König se cumple)' if nu == tau else '(König falla: no es bipartito)'}")

Now coloring. greedy colors in a given order, dsatur chooses the most saturated vertex at each step, and smallest_last constructs degeneracy order. To measure them we need exact χ\chi, computed on small graphs by backtracking that breaks color symmetry (vertex ii can introduce only the next new color, never skip one).

[ ]Greedy coloring, DSatur, and smallest-lastBrowser
def greedy(adj, order):
    color = {}
    for v in order:
        usados = {color[w] for w in adj[v] if w in color}
        c = 1
        while c in usados:
            c += 1
        color[v] = c
    return color

def dsatur(adj):
    color = {}
    while len(color) < len(adj):
        v = max((u for u in adj if u not in color),
                key=lambda u: (len({color[w] for w in adj[u] if w in color}), len(adj[u]), -u))
        usados = {color[w] for w in adj[v] if w in color}
        c = 1
        while c in usados:
            c += 1
        color[v] = c
    return color

def smallest_last(adj):
    deg, quedan, orden = {v: len(adj[v]) for v in adj}, set(adj), []
    while quedan:
        v = min(quedan, key=lambda u: (deg[u], u))
        orden.append(v)
        quedan.remove(v)
        for w in adj[v]:
            if w in quedan:
                deg[w] -= 1
    return orden[::-1]                           # se colorea en orden inverso al de eliminación

def chromatic(adj):
    vs = sorted(adj, key=lambda v: -len(adj[v]))
    def can(k):
        col = {}
        def bt(i, usados):
            if i == len(vs):
                return True
            v = vs[i]
            for c in range(1, min(k, usados + 1) + 1):
                if all(col.get(w) != c for w in adj[v]):
                    col[v] = c
                    if bt(i + 1, max(usados, c)):
                        return True
                    del col[v]
            return False
        return bt(0, 0)
    return next(k for k in range(1, len(adj) + 1) if can(k))

def is_proper(adj, color):
    return all(color[u] != color[v] for u in adj for v in adj[u])

def crown(n):
    adj = {v: [] for v in range(2 * n)}
    for i in range(n):
        for j in range(n):
            if i != j:
                adj[i].append(n + j)
                adj[n + j].append(i)
    return adj

print(" n | u1 v1 u2 v2 ... | un lado y otro | DSatur | último de menor grado")
for n in range(3, 9):
    adj = crown(n)
    alterno = [v for i in range(n) for v in (i, n + i)]
    cols = [max(greedy(adj, alterno).values()), max(greedy(adj, range(2 * n)).values()),
            max(dsatur(adj).values()), max(greedy(adj, smallest_last(adj)).values())]
    print(f"{n:2d} | {cols[0]:15d} | {cols[1]:14d} | {cols[2]:6d} | {cols[3]:21d}")

def gnp(n, p, r):
    adj = {v: [] for v in range(n)}
    for u, v in itertools.combinations(range(n), 2):
        if r.random() < p:
            adj[u].append(v)
            adj[v].append(u)
    return adj

exceso = {"voraz, orden al azar": [], "DSatur": [], "último de menor grado": []}
for _ in range(150):
    adj = gnp(12, 0.35, rng)
    chi = chromatic(adj)
    orden = list(adj)
    rng.shuffle(orden)
    for nombre, col in [("voraz, orden al azar", greedy(adj, orden)), ("DSatur", dsatur(adj)),
                        ("último de menor grado", greedy(adj, smallest_last(adj)))]:
        assert is_proper(adj, col)
        exceso[nombre].append(max(col.values()) - chi)
print("\n150 grafos G(12, 0.35):")
for nombre, ex in exceso.items():
    print(f"  {nombre:22s} óptima en el {sum(e == 0 for e in ex) / len(ex):.0%}, colores de más: media {sum(ex) / len(ex):.2f}, máximo {max(ex)}")

The crown table matches the interactive, now up to n=8n = 8: alternating order uses nn colors and the other three strategies use 2. On random graphs, greedy with a random order succeeds about half the time, and DSatur almost always, though neither guarantees anything.

For planarity, the “no” certificate computable from what we have seen is the girth bound. Girth is obtained by breadth-first search from every vertex: the first edge closing a cycle from ss gives a cycle of length d(u)+d(w)+1d(u) + d(w) + 1, and the minimum over all ss is exact.

[ ]Euler's bound as a nonplanarity certificateBrowser
def girth(adj):
    mejor = float("inf")
    for s in adj:
        dist, par, q = {s: 0}, {s: None}, deque([s])
        while q:
            u = q.popleft()
            for w in adj[u]:
                if w not in dist:
                    dist[w], par[w] = dist[u] + 1, u
                    q.append(w)
                elif par[u] != w:                # arista que cierra un ciclo
                    mejor = min(mejor, dist[u] + dist[w] + 1)
    return mejor

def euler_certifica_no_planar(adj):
    V, E, g = len(adj), sum(map(len, adj.values())) // 2, girth(adj)
    if g == float("inf") or V < 3:
        return False, V, E, g, None              # un bosque siempre es planar
    cota = g * (V - 2) / (g - 2)
    return E > cota, V, E, g, cota

def from_edges(n, edges):
    adj = {v: [] for v in range(n)}
    for u, v in edges:
        adj[u].append(v)
        adj[v].append(u)
    return adj

K33_edges = [(a, b) for a in range(3) for b in range(3, 6)]
grafos = {
    "K5": from_edges(5, itertools.combinations(range(5), 2)),
    "K3,3": from_edges(6, K33_edges),
    "Petersen": from_edges(10, [(i, (i + 1) % 5) for i in range(5)] + [(i, i + 5) for i in range(5)]
                           + [(5 + i, 5 + (i + 2) % 5) for i in range(5)]),
    "K3,3 + arista": from_edges(6, K33_edges + [(0, 1)]),
    "cubo": from_edges(8, [(i, (i + 1) % 4) for i in range(4)] + [(4 + i, 4 + (i + 1) % 4) for i in range(4)]
                       + [(i, i + 4) for i in range(4)]),
}
for nombre, adj in grafos.items():
    no, V, E, g, cota = euler_certifica_no_planar(adj)
    print(f"{nombre:14s} V = {V:2d}  E = {E:2d}  g = {g}  cota = {cota:5.2f}  ->  {'NO planar (certificado)' if no else 'la cota no decide'}")

The cube is on the bound, E=12=2V−4E = 12 = 2V - 4: all its faces are squares. “K3,3 + edge” reminds us that the bound does not decide every case; that requires Kuratowski, which we will use through networkx.

Finally, Ramsey. For each kk, the table compares the greatest nn with E[X]<1\E[X] < 1, the simplified version ⌊2k/2⌋\lfloor 2^{k/2} \rfloor, the deletion method, and the upper bound. Deletion improves the argument: take a coloring with X≤E[X]X \le \E[X] (one exists because not all can be above the mean) and remove one vertex from each monochromatic KkK_k; at least n−E[X]n - \E[X] vertices remain without any and, since their number is an integer, at least ⌈n−E[X]⌉\lceil n - \E[X] \rceil. Thus R(k,k)>⌈n−E[X]⌉R(k, k) > \lceil n - \E[X] \rceil for every nn, and the table takes the best nn. Then simulate the interactive and verify Paley’s coloring.

[ ]Ramsey bounds and Paley coloringBrowser
from math import comb, floor, ceil
import matplotlib.pyplot as plt

def umbral_erdos(k):
    n = k
    while comb(n + 1, k) * 2 ** (1 - comb(k, 2)) < 1:
        n += 1
    return n

def borrado(k):
    """Mejor cota del borrado: R(k, k) > ⌈n − E[X]⌉, maximizando en n."""
    return max(ceil(n - comb(n, k) * 2 ** (1 - comb(k, 2))) for n in range(k, 20 * 2 ** (k // 2)))

print(" k | E[X] < 1 hasta | ⌊2^(k/2)⌋ | borrado | cota superior C(2k−2, k−1)")
ks = list(range(3, 13))
for k in ks:
    print(f"{k:2d} | {umbral_erdos(k):14d} | {floor(2 ** (k / 2)):9d} | {borrado(k):7d} | {comb(2 * k - 2, k - 1):10d}")

def mono_count(n, k, rojo):
    return sum(len({rojo[u][v] for u, v in itertools.combinations(A, 2)}) == 1
               for A in itertools.combinations(range(n), k))

def coloracion_al_azar(n, r):
    rojo = [[None] * n for _ in range(n)]
    for u, v in itertools.combinations(range(n), 2):
        rojo[u][v] = rojo[v][u] = r.random() < 0.5
    return rojo

for n, k in [(6, 4), (7, 4), (10, 4)]:
    xs = [mono_count(n, k, coloracion_al_azar(n, rng)) for _ in range(1500)]
    EX = comb(n, k) * 2 ** (1 - comb(k, 2))
    print(f"n = {n:2d}, k = {k}: E[X] = {EX:.3f}, media = {sum(xs) / len(xs):.3f}, "
          f"P(X = 0) ≈ {xs.count(0) / len(xs):.3f}, garantía 1 − E[X] = {max(0.0, 1 - EX):.3f}")

cuadrados = {x * x % 17 for x in range(1, 17)}
paley = [[(v - u) % 17 in cuadrados if u != v else None for v in range(17)] for u in range(17)]
print(f"Paley 17: cuadrados = {sorted(cuadrados)}; K4 de un solo color = {mono_count(17, 4, paley)}; "
      f"al azar se esperarían {comb(17, 4) * 2 ** -5:.1f}")

fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.semilogy(ks, [umbral_erdos(k) + 1 for k in ks], "o-", label="inferior: E[X] < 1")
ax.semilogy(ks, [borrado(k) + 1 for k in ks], "s--", label="inferior: borrado")
ax.semilogy(ks, [comb(2 * k - 2, k - 1) for k in ks], "^-", label="superior: C(2k−2, k−1)")
ax.semilogy([3, 4], [6, 18], "k*", ms=12, label="valor exacto")
ax.vlines(5, 43, 46, colors="k", lw=3, label="R(5, 5) ∈ [43, 46]")
ax.set_xlabel("k"); ax.set_ylabel("R(k, k)  (escala log)")
ax.set_title("Lo que se sabe de R(k, k): un hueco exponencial")
ax.legend(fontsize=8); plt.tight_layout(); plt.show()

The simulation reproduces the interactive, and the table shows two facts worth reading carefully. First, exact condition E[X]<1\E[X] < 1 is much better than its simplification: for k=12k = 12 it gives 231 versus 64. Second, deletion never loses, because at the threshold E[X]<1\E[X] < 1 and ⌈n−E[X]⌉=n\lceil n - \E[X] \rceil = n, and from k=6k = 6 onward it wins by increasing margins: for k=12k = 12, 276 versus 231. Even so, it improves the bound only by a constant factor, 2\sqrt{2} asymptotically. In the plot, lower and upper bounds are nearly straight lines with different slopes on a logarithmic scale, 2 k\sqrt{2}^{\,k} versus 4k4^k, and the few known exact values fall between them.

The professional version

networkx implements all of the above. The important thing is knowing what each function does and its pitfalls, for which the verifiers you just wrote are the perfect tool.

FunctionWhat it doesWatch out for
bipartite.hopcroft_karp_matching(G, top_nodes)maximum matching in O(EV)\bigO(E\sqrt{V}), several augmenting paths per phasereturns a dictionary in both directions: its size is 2ν2\nu
bipartite.to_vertex_cover(G, M, top_nodes)König cover from a maximum matchingif MM is not maximum, the cover is not minimum and no longer certifies anything
nx.greedy_color(G, strategy)greedy coloring with an order: largest_first, smallest_last, DSATUR…all are greedy; none guarantees χ\chi
nx.check_planarity(G, counterexample=True)linear planarity test (left-right)returns a plane embedding or Kuratowski subgraph
[ ]networkx: Hopcroft–Karp, coloring, and planarityBrowser
import networkx as nx
from networkx.algorithms import bipartite
import time

# 1. Emparejamiento y cubrimiento de König: networkx frente al nuestro
r = random.Random(1)
for n in (150, 300):
    adj = {i: sorted(r.sample(range(n), 3)) for i in range(n)}
    top = [("x", i) for i in range(n)]
    B = nx.Graph()
    B.add_nodes_from(top, bipartite=0)
    B.add_nodes_from((("y", j) for j in range(n)), bipartite=1)
    B.add_edges_from((("x", i), ("y", j)) for i in adj for j in adj[i])
    t0 = time.perf_counter(); M_hk = bipartite.hopcroft_karp_matching(B, top_nodes=top)
    t1 = time.perf_counter(); C_nx = bipartite.to_vertex_cover(B, M_hk, top_nodes=top)
    t2 = time.perf_counter(); M, C, S = konig(adj, list(range(n)))
    t3 = time.perf_counter()
    print(f"n = {n}: ν = {len(M_hk) // 2} (Hopcroft-Karp, {1e3 * (t1 - t0):.0f} ms) = {len(M)} (nuestro); "
          f"|C| = {len(C_nx)} con to_vertex_cover en {1e3 * (t2 - t1):.0f} ms, nuestro König en {1e3 * (t3 - t2):.0f} ms")

# 2. Estrategias de greedy_color en la corona, con los vértices en el orden alterno
G = nx.Graph()
n = 20
G.add_nodes_from(v for i in range(n) for v in (f"u{i}", f"v{i}"))
G.add_edges_from((f"u{i}", f"v{j}") for i in range(n) for j in range(n) if i != j)
for s in ["largest_first", "smallest_last", "connected_sequential_bfs", "DSATUR"]:
    col = nx.greedy_color(G, strategy=s)
    print(f"corona n = {n}, {s:25s} {max(col.values()) + 1:2d} colores")

# 3. Planaridad con certificado en los dos sentidos
for nombre, H in [("Petersen", nx.petersen_graph()), ("K3,3 + arista", nx.Graph(K33_edges + [(0, 1)]))]:
    planar, cert = nx.check_planarity(H, counterexample=True)
    grados = sorted(d for _, d in cert.degree())
    print(f"{nombre}: planar = {planar}; subgrafo de Kuratowski con {cert.number_of_edges()} aristas, grados {grados}")
H = nx.triangular_lattice_graph(3, 4)
planar, emb = nx.check_planarity(H)
vistas, F = set(), 0
for u, v in emb.edges():                         # cada cara es una órbita de medias aristas
    if (u, v) not in vistas:
        emb.traverse_face(u, v, mark_half_edges=vistas)
        F += 1
V, E = H.number_of_nodes(), H.number_of_edges()
print(f"red triangular: planar = {planar}; V = {V}, E = {E}, F = {F}, V − E + F = {V - E + F}")

Three observations. First, largest_first, the default strategy of greedy_color, uses 20 colors on the crown because all degrees are equal and tie-breaking respects insertion order, which is alternating. Ordering by degree does not protect against the trap. Second, Petersen’s Kuratowski subgraph has six vertices of degree 3 and three of degree 2: it is a subdivision of K3,3K_{3,3}, the one highlighted in the interactive. Third, to_vertex_cover gives the correct cover, but its cost grows much faster than our construction, a single breadth-first search: compare times when doubling nn. If you need König covers on large graphs, use the twenty-line version from the previous section.

Common mistakes

Exercises

QuizWhere does König fail?
In which of these graphs is ν(G)≠τ(G)\nu(G) \ne \tau(G)?
NumericPetersen's chromatic number
The Petersen graph has 10 vertices: an outer pentagon p1,…,p5p_1, \dots, p_5, an inner pentagram p6,…,p10p_6, \dots, p_{10} (with p5+ip_{5+i} joined to p5+jp_{5+j} if j−i≡±2(mod5)j - i \equiv \pm 2 \pmod 5), and spokes pip5+ip_i p_{5+i}. What is its chromatic number?
QuizWhat greedy coloring guarantees
Which statement about greedy coloring holds for every graph GG?
QuizSatisfying Euler's bound
A simple connected graph with V≥3V \ge 3 satisfies E≤3V−6E \le 3V - 6. What can you conclude? (There may be multiple answers.)

More than one answer may be correct.

NumericPentagonal faces
A connected plane graph has all vertices of degree 3 and all faces pentagonal (degree 5). How many faces does it have?
NumericErdős's bound for k = 5
What is the largest nn for which Erdős's argument, namely (n5) 21−10<1\binom{n}{5}\, 2^{1 - 10} < 1, proves R(5,5)>nR(5, 5) > n?
NumericA bound that is exact
Use R(s,t)≤R(s−1,t)+R(s,t−1)R(s, t) \le R(s - 1, t) + R(s, t - 1), together with R(2,t)=tR(2, t) = t and R(3,4)=9R(3, 4) = 9, to bound R(3,5)R(3, 5). What bound do you obtain?
CodeHall's certificate
Implement hall_certificate(G, X, Y). G is a dictionary assigning each candidate in X the list of its neighbors in Y (which may be empty). Return ('matching', M), with M a candidate → position dictionary saturating X, or ('violator', S), with S a set of candidates such that ∣N(S)∣<∣S∣|N(S)| < |S|. The tests verify the certificate you return rather than comparing it with a fixed answer.
def hall_certificate(G, X, Y):
  # para cada candidato libre, busca un camino alternante hasta un puesto libre;
  # si no existe, los candidatos alcanzados forman el conjunto violador
  pass
Shift+Enter to run

Summary

Key idea
The great structural graph theorems are certificate theorems. Hall and König give short certificates in both directions for bipartite matching (the matching; a violating set or a cover of the same size), and Euler and Kuratowski do so for planarity. Coloring lacks them because it is NP-complete, and Ramsey proves existence without any certificate: a random coloring works.
  • Matchings. A matching is maximum if and only if there is no augmenting path (Berge). In bipartite graphs, alternating search finds a path or gets stuck at a set SS with ∣N(S)∣=∣S∣−1|N(S)| = |S| - 1: this proves Hall, ∣N(S)∣≥∣S∣|N(S)| \ge |S| for every SS, and the maximum deficiency is what the best matching lacks.
  • König. In bipartite graphs, ν=τ\nu = \tau, and cover (X∖Z)∪(Y∩Z)(X \setminus Z) \cup (Y \cap Z) comes from the same search. This is linear programming duality with integer solutions; it fails on a triangle.
  • Coloring. ω≤χ≤Δ+1\omega \le \chi \le \Delta + 1, with Brooks reducing this to Δ\Delta except for complete graphs and odd cycles. Greedy depends on order (on the crown, nn colors versus 2), an optimal order always exists, and DSatur and smallest-last are good heuristics without a general guarantee.
  • Planarity. V−E+F=2V - E + F = 2 in a connected plane graph; hence E≤3V−6E \le 3V - 6, E≤2V−4E \le 2V - 4 without triangles, and K5K_5, K3,3K_{3,3}, and Petersen are nonplanar. Kuratowski characterizes planarity, every planar graph has a vertex of degree ≤5\le 5, and 5 colors suffice (Kempe and Heawood). Four colors required a computer in 1976 and Coq in 2005.
  • Ramsey. R(s,t)≤R(s−1,t)+R(s,t−1)R(s, t) \le R(s - 1, t) + R(s, t - 1) by the pigeonhole principle, so R(k,k)<4kR(k, k) < 4^k; and R(k,k)>2k/2R(k, k) > 2^{k/2} because if E[X]<1\E[X] < 1 some coloring has X=0X = 0. An exponential gap between the two bounds remains open.