Three questions about networks
Matching. A university in Lagos offers final-year projects; each student lists the projects they would accept, and each project takes one student. Can every student get a project? If not, there must be a reason — and the reason, it turns out, is always the simplest one imaginable: some group of students who, between them, accept fewer than projects.
Drawing. Three houses each need a connection to three utilities — water, gas and electricity. Can the nine pipes be laid in a flat field without crossing? Circuit designers ask the same question about wires on a chip. The answer is no, and Euler's formula from 1752 explains why.
Unavoidable order. At any gathering of six people there are three who all know one another or three who are all strangers. At a gathering of five there need not be. In 1930 Frank Ramsey proved that this is a universal phenomenon: complete disorder is impossible — every sufficiently large structure contains a large orderly piece.
These are three of the central themes of graph theory: matchings, planarity and colouring, and extremal and Ramsey theory. This lesson builds on graphs (degrees, paths, trees, Euler circuits) and combinatorics (binomial coefficients and the pigeonhole principle).
Obstacles and their converses
Each theorem in this lesson has the same shape: there is an obvious obstacle to a property, and the theorem says that the obvious obstacle is the only one.
- A matching covering every student is impossible if some students accept fewer than projects. Hall's theorem: if no such group exists, a matching exists.
- A crossing-free drawing is impossible if the graph contains a copy of or , possibly with edges subdivided by extra vertices. Kuratowski's theorem: these are the only obstacles.
- In Ramsey theory there is not even an obstacle: no colouring of the edges of in two colours avoids a one-coloured triangle.
Theorems of this kind are useful in both directions. Exhibiting the obstacle certifies that the property fails, and the theorem guarantees such a certificate always exists — a pattern you will meet again in duality theorems of optimisation and in computational complexity.
Definitions
A graph here is finite and simple: is a set of 2-element subsets of , written . The degree is the number of edges at , and is the set of neighbours of ; for , . The handshake lemma says , since every edge has two ends.
Definition— bipartite graph, matching, vertex cover
is bipartite with parts and if and every edge joins to . A matching is a set of edges no two of which share a vertex; it covers a vertex set if every vertex of lies on one of its edges, and it is perfect if it covers . A vertex cover is a set meeting every edge. We write for the largest size of a matching and for the smallest size of a vertex cover.
Definition— planar graph, plane graph, faces
A graph is planar if it can be drawn in the plane with vertices as distinct points and edges as arcs that meet only at common endpoints. Such a drawing is a plane graph; the connected regions of the complement of the drawing are its faces, one of which is unbounded. A subdivision of a graph replaces edges by paths through new vertices of degree 2.
Definition— colouring, chromatic number
A proper -colouring assigns one of colours to each vertex so that adjacent vertices receive different colours. The chromatic number is the least for which one exists. The clique number is the largest size of a set of pairwise adjacent vertices; clearly .
Definition— Ramsey number, extremal number
The Ramsey number is the least such that every colouring of the edges of in red and blue contains a red or a blue . (That such an exists is Ramsey's theorem.) The extremal number is the largest number of edges of a graph on vertices containing no copy of .
Examples and non-examples
Example— Hall's obstacle
In the bipartite graph below, every vertex on the left has a neighbour, yet no matching covers the left side: the three highlighted vertices have only two neighbours between them, and . This graph was found by the experiment later in the lesson.
Example— Planar and non-planar graphs
is planar (draw a triangle with a vertex in the middle), and so is the cube graph . and — the utilities graph — are not (Corollary 6). The Petersen graph is not planar either: deleting one vertex and suppressing the resulting vertices of degree 2 reveals a subdivision of . A graph may have drawings with crossings and still be planar: the usual picture of as a square with both diagonals has a crossing, but moving one diagonal outside removes it.
Example— Chromatic numbers
Bipartite graphs with at least one edge have ; odd cycles have ; . The wheel (a 5-cycle plus a hub joined to all of it) has although it contains no : the odd rim needs three colours and the hub a fourth. The Petersen graph has . In general can be much larger than : Mycielski (1955) built triangle-free graphs of every chromatic number.
Example— A colouring of K5 with no monochromatic triangle
Colour the five sides of a regular pentagon red and the five diagonals (a pentagram) blue. Each colour class is a 5-cycle, which contains no triangle. So .
Matchings: Hall's and König's theorems
Theorem— Theorem 1 (Hall's marriage theorem, 1935)
Let be a bipartite graph with parts and . There is a matching covering if and only if
Proof
Necessity. If a matching covers , the partners of the vertices of are distinct vertices of .
Sufficiency, by strong induction on . If , Hall's condition gives the single vertex a neighbour. Let and assume the theorem for smaller . There are two cases.
Case 1: every nonempty proper subset has . Pick any and any neighbour of (one exists since ). Delete and . In the remaining graph, a nonempty has lost at most the one neighbour , so it still has at least neighbours. By induction, can be matched without using ; adding the edge covers .
Case 2: some nonempty proper has . The subgraph on satisfies Hall's condition (neighbourhoods of subsets of lie inside ), so by induction can be matched into . Now consider the graph on . For , its neighbours in are , and
So satisfies Hall's condition and, by induction, can be matched into . The two matchings use disjoint vertex sets; together they cover .
∎
The proof is a good example of the obstacle principle: when no subset is "tight", we have room to make a greedy choice; when a tight subset exists, it splits the problem into two independent smaller ones.
Theorem— Corollary 2 (regular bipartite graphs)
Every -regular bipartite graph with has a perfect matching.
Proof
Counting edges from each side gives , so . For , the edges leaving all end in , and the vertices of receive at most edges in total. So , Hall's condition holds, and a matching covering — hence perfect — exists.
∎
For example, every Latin rectangle on symbols with can be extended by another row to an Latin rectangle: the bipartite graph joining each column to the symbols still missing from it is -regular, and a perfect matching in it is the new row.
Theorem— Theorem 3 (König 1931, Egerváry 1931)
In a bipartite graph, the largest size of a matching equals the smallest size of a vertex cover: .
Proof
in every graph: a vertex cover must contain an endpoint of each edge of a matching, and these endpoints are distinct.
For , let be a minimum vertex cover, and . Let be the bipartite graph of edges between and . If some had fewer than neighbours in , then would be a smaller vertex cover: an edge at a vertex of ends either in or in . So satisfies Hall's condition for , and can be matched into . Symmetrically, can be matched into . The two matchings share no vertex, and together they have edges.
∎
König's theorem is a first example of linear-programming duality in combinatorics, and the matching it promises can be found efficiently by augmenting paths.
Planarity and colouring
Theorem— Theorem 4 (Euler's formula)
A connected plane graph with vertices, edges and faces satisfies .
Proof
Induction on . If is a tree, then , and a tree drawn in the plane does not separate it, so : .
Otherwise contains a cycle; let be an edge on it. The cycle is drawn as a simple closed curve, which by the Jordan curve theorem separates the plane into an inside and an outside, and has the inside on one side and the outside on the other. So the faces on the two sides of are different, and deleting merges them into one. The graph is still connected (the rest of the cycle joins the ends of ) and has vertices, edges and faces. By induction , which is the same equation.
∎
The proof uses two facts from plane topology — that a tree does not separate the plane, and the Jordan curve theorem — which are intuitive but not trivial; for drawings with polygonal edges they have elementary proofs.
Theorem— Corollary 5
A simple planar graph with vertices has . If it has no triangles, . Every simple planar graph has a vertex of degree at most .
Proof
We may assume is connected: otherwise join its components one at a time by new edges, drawn in the outer face. Each new edge joins two different components, so the graph stays simple, planar and (if it was) triangle-free, and only increases — so the inequalities for the new graph imply them for . Walk around the boundary of each face and count the edges met, an edge counted twice if the face lies on both its sides. Every edge is counted exactly twice in total, so the face lengths add up to . In a simple graph with at least three vertices, every face has length at least ; hence . Substituting from Euler's formula gives . Without triangles every face has length at least , so and . Finally, if every degree were at least then , contradicting .
∎
Theorem— Corollary 6
and are not planar.
Proof
has and . is bipartite, so it has no triangles, and .
∎
A subdivision of a non-planar graph is non-planar, so no planar graph contains a subdivision of or . The converse is the deep part:
Theorem— Theorem 7 (Kuratowski 1930)
A graph is planar if and only if it contains no subdivision of or of .
We omit the proof (Diestel, chapter 4, gives a complete one). Wagner's 1937 version says: planar if and only if neither nor is a minor (obtained by deleting and contracting edges). Robertson and Seymour's graph minor theorem (completed in 2004) vastly generalises this: every minor-closed family of graphs is characterised by finitely many excluded minors.
Theorem— Theorem 8 (Heawood 1890: the five colour theorem)
Every planar graph is 5-colourable.
Proof
Induction on the number of vertices. Let be a plane graph and a vertex of degree at most (Corollary 5). Colour with five colours by induction. If the neighbours of use at most four colours, give the fifth. Otherwise has five neighbours , in this cyclic order around in the drawing, coloured .
Let be the subgraph induced by the vertices coloured or (a Kempe chain subgraph). If and lie in different components of , swap colours and in the component of : the colouring stays proper, now has colour , and colour is free for . Otherwise a path in joins to , and together with the edges and it forms a cycle. By the cyclic order, this cycle separates from (Jordan curve theorem again), and every vertex on it has colour or , or is . So no path coloured and can join to : they lie in different components of . Swap colours and in the component of ; now colour is free for .
∎
Theorem— Theorem 9 (the four colour theorem: Appel and Haken 1976)
Every planar graph is 4-colourable.
The four colour problem was posed by Francis Guthrie in 1852. Alfred Kempe published a "proof" in 1879 using the chains above; Percy Heawood found the gap in 1890 and salvaged five colours. The proof by Kenneth Appel and Wolfgang Haken (1976) shows that every planar graph contains one of a finite list of unavoidable configurations (1,936 in the original proof, later reduced to 1,476), each of which is reducible (a colouring of the rest extends), and it checks reducibility by computer. Robertson, Sanders, Seymour and Thomas (1997) gave a simpler proof with 633 configurations, still computer-assisted; Georges Gonthier and Benjamin Werner formalised a complete proof in the Coq proof assistant (2005), removing doubts about the correctness of the programs. No proof checkable by hand is known. Deciding whether a planar graph is 3-colourable, by contrast, is NP-complete.
Extremal graphs and Ramsey numbers
Theorem— Theorem 10 (Mantel 1907)
A triangle-free graph on vertices has at most edges. The complete bipartite graph shows that this is best possible.
Proof
Let be triangle-free. For every edge , the neighbourhoods and are disjoint — a common neighbour would close a triangle — so . Summing over all edges, and noting that each vertex appears in the sum once for each of its edges,
By the Cauchy–Schwarz inequality and the handshake lemma, . So , and since is an integer, . Finally is bipartite, hence triangle-free, with edges.
∎
Theorem— Theorem 11 (Turán 1941)
A graph on vertices with no has at most as many edges as the Turán graph , the complete -partite graph with parts of sizes as equal as possible; and is the only extremal graph. In particular .
One proof (Zykov's symmetrisation) shows that a -free graph with the most edges must be complete multipartite — if two non-adjacent vertices had different degrees, replacing the one of smaller degree by a copy of the other would add edges without creating a — and then that the parts must be balanced. Mantel's theorem is the case . The Erdős–Stone theorem (1946), in the form noted by Erdős and Simonovits (1966), extends Turán's theorem asymptotically to every forbidden graph : .
Theorem— Theorem 12 (R(3, 3) = 6)
Every red–blue colouring of the edges of contains a monochromatic triangle, and some colouring of does not.
Proof
The pentagon colouring above handles . In a colouring of , fix a vertex . It has five edges, so by the pigeonhole principle at least three of them, say , , , have the same colour — red, say. If any of , , is red, it forms a red triangle with . If none is, then is a blue triangle.
∎
Theorem— Theorem 13 (Ramsey 1930; Erdős and Szekeres 1935)
For , exists and . Consequently , and in particular .
Proof
First, and : a colouring of has a blue edge or is entirely red. Now suppose and exist, let , and colour the edges of . A vertex has edges, so it has at least red neighbours or at least blue neighbours (otherwise ). In the first case, the red neighbours contain a blue , or a red which together with is a red . The second case is symmetric. So .
The binomial bound follows by induction on , since (Pascal's rule) and the base cases agree: , .
∎
Theorem— Theorem 14 (Erdős 1947)
For , .
Proof
Let and colour each edge of red or blue independently with probability . A fixed set of vertices spans edges, so it is monochromatic with probability . By linearity of expectation, the expected number of monochromatic 's is
A random variable taking non-negative integer values with mean less than is with positive probability. So some colouring of has no monochromatic , and .
∎
The proof shows that most colourings work, yet nobody knows how to construct one explicitly that comes close to . So ; in 2023 Campos, Griffiths, Morris and Sahasrabudhe lowered the upper base from to for a small , the first exponential improvement in decades. The exact values and (Greenwood and Gleason, 1955) are known; is known only to lie between and .
Graph theory in Lean and Mathlib
Mathlib's SimpleGraph V is a symmetric, irreflexive adjacency relation on a type V, with finite edge sets G.edgeFinset when V is finite. The handshake lemma comes from the library:
/-- **The handshake lemma**: the degrees of a finite graph add up to twice the number of edges.
This applies Mathlib's `SimpleGraph.sum_degrees_eq_twice_card_edges`. -/
theorem handshake {V : Type*} [Fintype V] [DecidableEq V] (G : SimpleGraph V)
[DecidableRel G.Adj] : ∑ v, G.degree v = 2 * #G.edgeFinset :=
G.sum_degrees_eq_twice_card_edgesHall's theorem is stated in Mathlib for a family of finite sets t : ι → Finset α — the neighbourhoods of the vertices of — and a matching is an injective choice function. The easy direction is proved here, mirroring the proof above; the full theorem is quoted from Mathlib, which proves it for any index type, even an infinite one (that needs a compactness argument; see the logician's viewpoint below):
/-- **Hall's condition is necessary.** If every `i` can be matched to its own `f i ∈ t i`, with
different `i` getting different elements, then any `k` indices have at least `k` neighbours
between them: the images `f i` of the indices in `s` are `#s` distinct neighbours. -/
theorem hall_necessary {ι α : Type*} [DecidableEq α] (t : ι → Finset α) (f : ι → α)
(hf : Function.Injective f) (hft : ∀ i, f i ∈ t i) (s : Finset ι) :
#s ≤ #(s.biUnion t) := by
have hsub : s.image f ⊆ s.biUnion t := by
intro a ha
obtain ⟨i, hi, rfl⟩ := mem_image.1 ha
exact mem_biUnion.2 ⟨i, hi, hft i⟩
calc #s = #(s.image f) := (card_image_of_injective s hf).symm
_ ≤ #(s.biUnion t) := card_le_card hsub/-- **Hall's marriage theorem** (P. Hall, 1935): a family of finite sets `t i` has a system of
distinct representatives if and only if every `k` of the sets together contain at least `k`
elements. Mathlib proves it for an arbitrary (even infinite) index type, which needs a
compactness argument on top of the finite case. This applies
`Finset.all_card_le_biUnion_card_iff_exists_injective`. -/
theorem hall {ι α : Type*} [DecidableEq α] (t : ι → Finset α) :
(∀ s : Finset ι, #s ≤ #(s.biUnion t)) ↔ ∃ f : ι → α, Function.Injective f ∧ ∀ i, f i ∈ t i :=
Finset.all_card_le_biUnion_card_iff_exists_injective tPlanarity. Mathlib does not yet define plane embeddings, so Euler's formula cannot be stated there. What can be formalised is the counting step of Corollaries 5 and 6, with Euler's formula as a hypothesis:
/-- **The edge bound for plane graphs.** If a connected plane graph has `V` vertices, `E` edges
and `F` faces, Euler's formula gives `V − E + F = 2`. If every face is bounded by at least three
edges, counting edge–face incidences gives `3F ≤ 2E`. Together: `E ≤ 3V − 6`. -/
theorem planar_edge_bound (V E F : ℤ) (euler : V - E + F = 2) (faces : 3 * F ≤ 2 * E) :
E ≤ 3 * V - 6 := by
omega/-- Without triangles (for instance in a bipartite graph) every face has at least four edges,
so `4F ≤ 2E`, and Euler's formula gives `E ≤ 2V − 4`. -/
theorem planar_edge_bound_bipartite (V E F : ℤ) (euler : V - E + F = 2)
(faces : 4 * F ≤ 2 * E) : E ≤ 2 * V - 4 := by
omega/-- K₅ (5 vertices, 10 edges) violates `E ≤ 3V − 6`, and K₃,₃ (6 vertices, 9 edges, no
triangles) violates `E ≤ 2V − 4`. Combined with the two bounds above, this is the proof that
neither graph is planar — given Euler's formula, which is not formalised here. -/
theorem k5_k33_too_many_edges : ¬ ((10 : ℤ) ≤ 3 * 5 - 6) ∧ ¬ ((9 : ℤ) ≤ 2 * 6 - 4) := by
omegaMantel and Turán from Mathlib, whose proof of Turán's theorem shows that a -free graph with the most edges is isomorphic to the Turán graph:
/-- **Mantel's theorem** (1907): a triangle-free graph on `n` vertices has at most `⌊n² / 4⌋`
edges. This is the case `r = 2` of Turán's theorem, applying Mathlib's
`SimpleGraph.CliqueFree.card_edgeFinset_le` and `SimpleGraph.turanNumber_two`. -/
theorem mantel {V : Type*} [Fintype V] [DecidableEq V] (G : SimpleGraph V) [DecidableRel G.Adj]
(h : G.CliqueFree 3) : #G.edgeFinset ≤ Fintype.card V ^ 2 / 4 := by
have := SimpleGraph.CliqueFree.card_edgeFinset_le (r := 2) h
rwa [SimpleGraph.turanNumber_two] at this/-- **Turán's theorem** (1941), in the convenient form `|E| ≤ (1 − 1/r) n² / 2` for graphs with no
clique of size `r + 1`, written without division. This combines Mathlib's
`SimpleGraph.CliqueFree.card_edgeFinset_le` and `SimpleGraph.mul_turanNumber_le`. -/
theorem turan {V : Type*} [Fintype V] [DecidableEq V] (G : SimpleGraph V) [DecidableRel G.Adj]
(r : ℕ) (h : G.CliqueFree (r + 1)) :
2 * r * #G.edgeFinset ≤ (r - 1) * Fintype.card V ^ 2 :=
calc 2 * r * #G.edgeFinset ≤ 2 * r * SimpleGraph.turanNumber (Fintype.card V) r :=
Nat.mul_le_mul_left _ (SimpleGraph.CliqueFree.card_edgeFinset_le h)
_ ≤ (r - 1) * Fintype.card V ^ 2 := SimpleGraph.mul_turanNumber_leR(3, 3) = 6, both halves proved here. Edges are unordered pairs s(a, b) : Sym2 (Fin n), so a colouring is any function Sym2 (Fin n) → Bool. The lower bound is checked by evaluation; the upper bound follows the pigeonhole proof of Theorem 12:
/-- A red–blue colouring of the edges of K₅: an edge is red (`true`) if it is a side of the
pentagon 0–1–2–3–4–0, and blue (`false`) if it is a diagonal (the pentagram). -/
def pentagon (e : Sym2 (Fin 5)) : Bool :=
decide (e ∈ [s(0, 1), s(1, 2), s(2, 3), s(3, 4), s(4, 0)])/-- **R(3, 3) > 5.** The pentagon colouring of K₅ has no monochromatic triangle: the red graph
(a 5-cycle) and the blue graph (another 5-cycle) contain no triangles. Checked by `decide` over
all `5³` triples. -/
theorem pentagon_no_mono_triangle :
∀ a b d : Fin 5, a ≠ b → b ≠ d → a ≠ d →
¬ (pentagon s(a, b) = pentagon s(b, d) ∧ pentagon s(b, d) = pentagon s(a, d)) := by
decide/-- **The pigeonhole step.** Among five edges coloured with two colours, three share a colour:
if at most two were red, at least three would be blue. -/
theorem three_of_five (f : Fin 5 → Bool) :
∃ col : Bool, ∃ x y z : Fin 5, x ≠ y ∧ x ≠ z ∧ y ≠ z ∧
f x = col ∧ f y = col ∧ f z = col := by
have hsplit := card_filter_add_card_filter_not (s := (univ : Finset (Fin 5)))
(fun k => f k = true)
rw [card_univ, Fintype.card_fin] at hsplit
by_cases h3 : 2 < #(univ.filter fun k : Fin 5 => f k = true)
· obtain ⟨x, y, z, hx, hy, hz, hxy, hxz, hyz⟩ := two_lt_card_iff.1 h3
simp only [mem_filter, mem_univ, true_and] at hx hy hz
exact ⟨true, x, y, z, hxy, hxz, hyz, hx, hy, hz⟩
· have h3' : 2 < #(univ.filter fun k : Fin 5 => ¬ f k = true) := by omega
obtain ⟨x, y, z, hx, hy, hz, hxy, hxz, hyz⟩ := two_lt_card_iff.1 h3'
simp only [mem_filter, mem_univ, true_and, Bool.not_eq_true] at hx hy hz
exact ⟨false, x, y, z, hxy, hxz, hyz, hx, hy, hz⟩/-- **R(3, 3) ≤ 6: every red–blue colouring of the edges of K₆ has a monochromatic triangle.**
The proof of the lesson: vertex `0` has five edges, so three of them, to `x, y, z`, share a
colour `col` (`three_of_five`). If any edge among `x, y, z` also has colour `col`, it forms a
triangle with `0`; otherwise all three edges among `x, y, z` have the other colour. -/
theorem ramsey_three_three (c : Sym2 (Fin 6) → Bool) :
∃ a b d : Fin 6, a ≠ b ∧ b ≠ d ∧ a ≠ d ∧ c s(a, b) = c s(b, d) ∧ c s(b, d) = c s(a, d) := by
-- Step 1: three edges at vertex 0 with the same colour. Vertex `k.succ` is the `k`-th neighbour.
obtain ⟨col, x, y, z, hxy, hxz, hyz, hx, hy, hz⟩ := three_of_five fun k => c s(0, k.succ)
have h0x : (0 : Fin 6) ≠ x.succ := (Fin.succ_ne_zero x).symm
have h0y : (0 : Fin 6) ≠ y.succ := (Fin.succ_ne_zero y).symm
have h0z : (0 : Fin 6) ≠ z.succ := (Fin.succ_ne_zero z).symm
have hxy' : x.succ ≠ y.succ := fun h => hxy (Fin.succ_inj.1 h)
have hxz' : x.succ ≠ z.succ := fun h => hxz (Fin.succ_inj.1 h)
have hyz' : y.succ ≠ z.succ := fun h => hyz (Fin.succ_inj.1 h)
-- Step 2: an edge among `x, y, z` of colour `col` closes a triangle with `0`.
by_cases e1 : c s(x.succ, y.succ) = col
· exact ⟨0, x.succ, y.succ, h0x, hxy', h0y, hx.trans e1.symm, e1.trans hy.symm⟩
by_cases e2 : c s(x.succ, z.succ) = col
· exact ⟨0, x.succ, z.succ, h0x, hxz', h0z, hx.trans e2.symm, e2.trans hz.symm⟩
by_cases e3 : c s(y.succ, z.succ) = col
· exact ⟨0, y.succ, z.succ, h0y, hyz', h0z, hy.trans e3.symm, e3.trans hz.symm⟩
-- Step 3: otherwise `x, y, z` form a triangle of the other colour.
exact ⟨x.succ, y.succ, z.succ, hxy', hyz', hxz', bool_eq_of_ne_of_ne e1 e3,
bool_eq_of_ne_of_ne e3 e2⟩What is not formalised here: Euler's formula and Kuratowski's theorem (no plane embeddings in Mathlib yet), the five and four colour theorems (the four colour theorem is formalised in Coq), König's theorem, the general Ramsey bounds and Erdős's probabilistic lower bound.
Checking every colouring, and testing Hall
There are only red–blue colourings of , so a computer can check Theorem 12 directly — and find more: every colouring has at least two monochromatic triangles (a theorem of Goodman, 1959). It also confirms that the twelve colourings of without a monochromatic triangle are exactly the pentagon–pentagram colourings, and tabulates the lower bounds that Erdős's argument gives.
"""R(3, 3) = 6 by exhaustive search, Goodman's count, and Erdos's random bound.
A red-blue colouring of the 15 edges of K6 is a 15-bit number, so there are
2^15 = 32768 colourings. We check every one for a monochromatic triangle,
count the fewest monochromatic triangles any colouring can have (Goodman
proved in 1959 that it is 2 for K6), and list the colourings of K5 with no
monochromatic triangle. This exhaustive check is a complete proof of
R(3, 3) = 6, provided the code is right.
For larger k exhaustive search is hopeless (K18 has 153 edges). Erdos's 1947
argument instead shows that a *random* colouring of K_n has, on average,
fewer than one monochromatic K_k when C(n, k) * 2^(1 - C(k, 2)) < 1, so some
colouring has none and R(k, k) > n. We tabulate the n this gives.
"""
import itertools
import math
def edge_index(n):
"""Map each edge (a, b), a < b, of K_n to a bit position."""
return {e: k for k, e in enumerate(itertools.combinations(range(n), 2))}
def triangle_masks(n):
"""Bit masks of the three edges of each triangle of K_n."""
idx = edge_index(n)
return [(1 << idx[(a, b)]) | (1 << idx[(a, c)]) | (1 << idx[(b, c)])
for a, b, c in itertools.combinations(range(n), 3)]
def mono_triangles(colouring, masks):
"""Number of triangles whose edges are all red (bit 1) or all blue (0)."""
return sum(1 for m in masks if colouring & m in (0, m))
def census(n):
"""Monochromatic-triangle counts of all 2^C(n,2) colourings of K_n."""
masks = triangle_masks(n)
return [mono_triangles(c, masks) for c in range(1 << math.comb(n, 2))]
def red_graph_is_five_cycle(colouring):
"""For K5: is the red graph a 5-cycle (connected and 2-regular)?"""
idx = edge_index(5)
red = [e for e, k in idx.items() if colouring >> k & 1]
degree = [sum(v in e for e in red) for v in range(5)]
if len(red) != 5 or any(d != 2 for d in degree):
return False
seen, todo = {0}, [0]
while todo:
v = todo.pop()
for a, b in red:
w = b if a == v else a if b == v else None
if w is not None and w not in seen:
seen.add(w)
todo.append(w)
return len(seen) == 5
def erdos_bound(k):
"""Largest n with C(n, k) * 2^(1 - C(k, 2)) < 1, so that R(k, k) > n."""
n = k
while math.comb(n + 1, k) * 2 < 2 ** math.comb(k, 2):
n += 1
return n
def main():
six = census(6)
print(f"K6: {len(six)} colourings of 15 edges")
print(f" with no monochromatic triangle: {six.count(0)}")
print(f" fewest monochromatic triangles: {min(six)} "
f"(attained by {six.count(min(six))} colourings)")
five = census(5)
good = [c for c, t in enumerate(five) if t == 0]
print(f"K5: {len(five)} colourings; with no monochromatic triangle: "
f"{len(good)}")
print(f" red graph a 5-cycle in each of them: "
f"{all(red_graph_is_five_cycle(c) for c in good)}")
print("So R(3, 3) = 6: K6 always has a monochromatic triangle, K5 need not.")
print()
print("Erdos (1947): a random colouring shows R(k, k) > n for these n")
print(" k n (Erdos) 2^(k/2) known R(k, k)")
known = {3: "6", 4: "18", 5: "43 to 46"}
for k in range(3, 11):
print(f"{k:>4} {erdos_bound(k):>11} {2 ** (k / 2):>9.1f} "
f"{known.get(k, 'not known')}")
print()
print("Epistemic status: the K5 and K6 results are exact and exhaustive, "
"so they\nprove R(3, 3) = 6 and Goodman's minimum for K6, assuming "
"this code is\ncorrect. The Erdos column is exact arithmetic for a "
"proved bound; the\n'known' column is quoted from the literature, "
"not computed here.")
if __name__ == "__main__":
main()The exhaustive part is a computer-assisted proof, as trustworthy as the code; the Lean proof above is the same theorem with a machine-checked proof. Exhaustive search does not scale: has colourings, and even is out of reach.
The second program tests Hall's theorem on random bipartite graphs: it compares Hall's condition, checked on all subsets, with the result of the augmenting-path algorithm, and also checks the deficiency form of Hall's theorem, , and König's theorem.
"""Hall's condition, augmenting paths and Konig's theorem on random graphs.
For a bipartite graph with parts A and B, Hall's theorem says: there is a
matching covering A if and only if |N(S)| >= |S| for every S subset of A.
We test it on 400 seeded random bipartite graphs with |A| = |B| = 5:
* Hall's condition is checked directly, over all 2^5 subsets S of A;
* a maximum matching is found by augmenting paths (Kuhn's algorithm);
* the deficiency form of Hall's theorem, max matching = |A| - max(|S| -
|N(S)|), and Konig's theorem, max matching = min vertex cover (found by
brute force over all 2^10 vertex sets), are checked as well.
This is experimental evidence on small graphs. The proofs are in the lesson.
"""
import itertools
import random
def random_bipartite(a, b, p, rng):
"""Neighbour sets N(i) in range(b) for each i in range(a)."""
return [frozenset(j for j in range(b) if rng.random() < p) for _ in range(a)]
def neighbourhood(adj, subset):
"""N(S): all vertices of B adjacent to some vertex of S."""
out = set()
for i in subset:
out |= adj[i]
return out
def hall_violator(adj):
"""A set S with |N(S)| < |S|, or None if Hall's condition holds."""
for size in range(1, len(adj) + 1):
for subset in itertools.combinations(range(len(adj)), size):
if len(neighbourhood(adj, subset)) < size:
return subset
return None
def max_deficiency(adj):
"""max over S of |S| - |N(S)|, including S = empty set (value 0)."""
return max(len(s) - len(neighbourhood(adj, s))
for size in range(len(adj) + 1)
for s in itertools.combinations(range(len(adj)), size))
def maximum_matching(adj):
"""Kuhn's augmenting-path algorithm; return a dict B-vertex -> A-vertex."""
match = {}
def augment(i, seen):
for j in sorted(adj[i]):
if j not in seen:
seen.add(j)
if j not in match or augment(match[j], seen):
match[j] = i
return True
return False
for i in range(len(adj)):
augment(i, set())
return match
def min_vertex_cover(adj, b):
"""Smallest set of vertices touching every edge, by brute force."""
edges = [(i, j) for i, nbrs in enumerate(adj) for j in nbrs]
vertices = [("A", i) for i in range(len(adj))] + [("B", j) for j in range(b)]
for size in range(len(vertices) + 1):
for cover in itertools.combinations(vertices, size):
chosen = set(cover)
if all(("A", i) in chosen or ("B", j) in chosen for i, j in edges):
return size
return len(vertices)
def main():
rng = random.Random(1935)
a = b = 5
graphs = [random_bipartite(a, b, rng.choice([0.25, 0.35, 0.5]), rng)
for _ in range(400)]
hall_ok = covering = agree = deficiency_ok = konig_ok = 0
example = None
for adj in graphs:
violator = hall_violator(adj)
m = len(maximum_matching(adj))
hall_ok += violator is None
covering += m == a
agree += (violator is None) == (m == a)
deficiency_ok += m == a - max_deficiency(adj)
konig_ok += m == min_vertex_cover(adj, b)
interesting = violator is not None and len(violator) >= 2
if interesting and example is None and all(adj):
example = (adj, violator)
print(f"400 random bipartite graphs, |A| = |B| = {a}")
print(f" Hall's condition holds: {hall_ok}")
print(f" a matching covers A (augmenting): {covering}")
print(f" the two answers agree: {agree}/400")
print(f" max matching = |A| - max deficiency: {deficiency_ok}/400")
print(f" max matching = min vertex cover: {konig_ok}/400")
adj, s = example
nbrs = sorted(neighbourhood(adj, s))
print("A graph failing Hall's condition, though every vertex has a neighbour:")
for i, row in enumerate(adj):
print(f" a{i} -> {sorted(row)}")
print(f" S = {[f'a{i}' for i in s]} has only {len(nbrs)} neighbours {nbrs}")
print()
print("Epistemic status: exact computations on 400 seeded random graphs, "
"all\nconsistent with Hall's theorem, its deficiency form and Konig's "
"theorem.\nThis is experimental evidence for small graphs; the "
"theorems are proved in\nthe lesson (and Hall's theorem in Lean).")
if __name__ == "__main__":
main()Explore: degrees, colourings and the two forbidden graphs
Planarity, colouring and degrees
Dots joined by lines: count degrees, walk along edges, colour vertices, grow spanning trees and count walks with a matrix.
0
colours used
0
clashes
6
uncoloured
Give every vertex a colour so that the two ends of each edge differ.
This graph is not planar (it cannot be drawn without edges crossing), so the Four Colour Theorem does not apply to it.
Things to try:
- On and , use the degree tab to read off and and check them against and .
- Colour the wheel with as few colours as you can; then ask for "Fewest possible?". Why can the odd rim not be done with two colours?
- The Petersen graph is 3-regular with 10 vertices: check the handshake lemma, then find a 3-colouring by hand. Does it have a perfect matching? (Yes — try to find five disjoint edges. Petersen's theorem (1891) says every bridgeless 3-regular graph has one.)
Exercises
1. Graph theory
Warm-upHumanA graph has seven vertices with degrees . How many edges does it have?
2. Graph theory
Warm-upHumanA connected plane graph has vertices and edges. How many faces does it have (counting the unbounded face)?
3. Graph theory
CoreHumanWhat is the largest number of edges in a triangle-free graph on vertices?
4. Graph theory
CoreHumanWhich of these graphs are planar? (Select all that apply.)
5. Graph theory
StretchHumanCorollary 5 says: a planar graph with vertices has . Which of the hypotheses are genuinely needed, in the sense that dropping one of them gives a counterexample? (Select all that apply.)
6. Graph theory
CoreHumanThe proof that every red–blue colouring of has a monochromatic triangle starts: "a vertex has five edges, so three of them share a colour". If we try the same proof on , where does it break down?
7. Graph theory
CoreHumanThe Erdős–Szekeres bound says . What upper bound does it give for ?
8. Graph theory
CoreFormalEdges of are unordered pairs s(a, b) : Sym2 (Fin 6), and a red–blue colouring is a function c : Sym2 (Fin 6) → Bool. Which Lean statement says that every colouring has a monochromatic triangle?
9. Graph theory
StretchComputationalA bipartite graph is given as a list adj, where adj[i] is the set of neighbours (in ) of vertex of . Write hall_violator(adj) that returns a smallest set , as a sorted tuple of indices, with , or None if Hall's condition holds (so that, by Hall's theorem, a matching covering exists).
Common misconceptions
Misconception
"A graph is planar if the drawing in front of me has no crossings — or non-planar if it has some." Planarity is about some drawing. The square-with-diagonals picture of has a crossing, yet is planar. To prove non-planarity you need an argument covering every drawing, such as Euler's formula or Kuratowski's theorem.
Misconception
"The four colour theorem has a short proof that can be checked by hand." No such proof is known. All known proofs rely on computer verification of hundreds of configurations; the computations were themselves verified in a formal proof assistant (Coq) in 2005. The five colour theorem, by contrast, has the short proof above.
Misconception
"Hall's condition only needs to be checked for single vertices." Every vertex having a neighbour is far from enough: in the example above every left vertex has a neighbour, but three of them share only two. The condition must hold for every subset — which is why checking it directly takes exponential time, while augmenting paths find a matching in polynomial time.
Misconception
"R(3, 3) = 6 means that six people always include three mutual friends." It means three mutual friends or three mutual strangers. Either alternative alone can fail: if nobody knows anybody, there are no friends at all.
Misconception
" is determined by the largest clique." , but the gap can be arbitrarily large: there are triangle-free graphs () of any chromatic number (Mycielski 1955; Erdős 1959 showed there are even graphs with no short cycles at all and huge chromatic number).
Many ways of seeing
Topology— Euler characteristic and graphs on surfaces
A graph is a 1-dimensional cell complex, and Euler's formula is the statement that the sphere has Euler characteristic . On a closed orientable surface of genus (a sphere with handles), a graph drawn so that every face is a disc satisfies , and the argument of Corollary 5 gives . From this Heawood (1890) derived that every graph embeddable on that surface can be coloured with colours when , and Ringel and Youngs (1968) proved the bound is attained — so the "map colour problem" was solved for every surface except the sphere before the four colour theorem. Even the graph itself carries topology: its first Betti number ( = number of components) counts independent cycles, and the fundamental group of a connected graph is free of that rank. See surfaces and Euler characteristic and the fundamental group.
Geometry— Straight lines, circles and polyhedra
Planarity is more geometric than it looks. Fáry's theorem (Wagner 1936, Fáry 1948): every planar graph can be drawn with straight-line edges. The Koebe–Andreev–Thurston circle packing theorem: every planar graph is the tangency graph of a family of interior-disjoint discs in the plane. Steinitz's theorem (1922): the graphs of convex polyhedra in are exactly the 3-connected planar graphs. In the other direction, geometry produces hard graph problems: the Hadwiger–Nelson problem asks for the chromatic number of the graph on all points of the plane with edges between points at distance . It is known to be , or ; the lower bound is due to Aubrey de Grey (2018), via a unit-distance graph with 1,581 vertices whose non-4-colourability was checked by computer. See Euclidean geometry.
Algebra— Matrices that know about graphs
Linear algebra sees a graph through its adjacency matrix : the entry counts walks of length , and . Its eigenvalues bound combinatorial quantities — for a -regular graph with smallest eigenvalue , Hoffman's bound says every independent set has at most vertices. Kirchhoff's matrix-tree theorem (1847) counts spanning trees as a determinant of the Laplacian with a row and column deleted. And matchings are algebra too: Tutte (1947) showed that a graph has a perfect matching iff its Tutte matrix — skew-symmetric, with an indeterminate for each edge — has non-zero determinant. Substituting random numbers gives Lovász's fast randomised matching test (1979). In a bipartite graph the corresponding determinant is the Edmonds matrix, and the permanent of its 0–1 version counts perfect matchings. See linear algebra.
Probability— Random graphs and the probabilistic method
Erdős's proof of Theorem 14 founded the probabilistic method: to show an object exists, show a random one has the property with positive probability. Erdős and Rényi (1959–60) then studied the random graph , with each edge present independently with probability , and found sharp thresholds: if , the probability that is connected tends to , so connectivity switches on abruptly around ; and a "giant component" appears at . Random graphs give the best known lower bounds for Ramsey numbers and many extremal problems, and they are a model for networks of every kind. See the probabilistic method and probability theory.
Logic— From finite to infinite: compactness
Do the theorems survive for infinite graphs? The de Bruijn–Erdős theorem (1951): an infinite graph is -colourable if and only if every finite subgraph is. Its proof is an application of the compactness theorem of first-order logic (or of Tychonoff's theorem for products of finite sets), and it needs a weak form of the axiom of choice; so, by the four colour theorem, every infinite planar graph is 4-colourable too. Hall's theorem extends in the same way to infinite families of finite sets (Marshall Hall, 1948), which is how Mathlib proves it. It fails without finiteness: the family , for satisfies Hall's condition for every finite subfamily, but has no system of distinct representatives. Ramsey's theorem itself was proved in a paper on logic ("On a problem of formal logic", 1930), and has an infinite version: every 2-colouring of the pairs of has an infinite monochromatic set. Paris and Harrington (1977) found a mild strengthening of the finite Ramsey theorem that is true but unprovable in Peano arithmetic — the first natural example of Gödel incompleteness. See compactness and incompleteness.
Computation— Which graph problems are easy?
Matchings are easy: augmenting paths give in polynomial time for bipartite graphs (Hopcroft–Karp runs in ), and Edmonds's blossom algorithm (1965) handles general graphs. Planarity can be tested in linear time (Hopcroft and Tarjan, 1974). Colouring is hard: deciding 3-colourability is NP-complete, even for planar graphs, while 4-colourability of planar graphs is trivial to decide — the answer is always yes, by the four colour theorem — and a 4-colouring can be found in quadratic time by the method of Robertson, Sanders, Seymour and Thomas. Hall's theorem explains why bipartite matching is easy: a violated Hall condition is a short certificate that no matching exists, so the problem is in , the typical home of polynomial-time problems with min–max theorems. See computational complexity and algorithm design.
History and global context
- Early tours. Knight's tours of the chessboard — Hamiltonian paths in the knight's-move graph — appear in Arabic chess manuscripts and in the 9th-century Sanskrit poetics of Rudraṭa, as verse patterns. Leonhard Euler's solution of the Königsberg bridges problem (1736) is usually taken as the beginning of graph theory; his formula for polyhedra followed in 1752 (a related result is found in notes of René Descartes from around 1630).
- Trees, circuits and maps. Gustav Kirchhoff's work on electrical networks (1847) contains the matrix-tree theorem; Arthur Cayley counted trees ( labelled trees on vertices, 1889). Francis Guthrie posed the four colour problem in 1852; Kempe's flawed proof (1879) and Heawood's five colour theorem (1890) followed.
- The Hungarian school. Dénes Kőnig wrote the first book on graph theory (1936). Kőnig and Jenő Egerváry proved the min–max theorem for bipartite matchings (1931); Harold Kuhn later named his assignment algorithm the "Hungarian method" in their honour (1955). Pál Turán found his theorem in 1941 while in a forced labour camp. Paul Erdős, with collaborators all over the world, founded extremal graph theory, random graphs and the probabilistic method.
- Matchings and planarity. Philip Hall proved his theorem in 1935 for sets of representatives. Kazimierz Kuratowski characterised planar graphs in 1930 (Frink and Smith found the theorem independently, and Pontryagin had obtained it earlier without publishing).
- Ramsey theory. Frank Ramsey (1903–1930) proved his theorem as a lemma in logic shortly before his death at 26. Erdős and George Szekeres rediscovered it in 1935 in a geometric problem (the "happy ending problem" on convex polygons). Greenwood and Gleason found in 1955.
- The computer era. Appel and Haken proved the four colour theorem in 1976; Robertson, Sanders, Seymour and Thomas simplified it in 1997; Gonthier and Werner formalised it in 2005. Robertson and Seymour completed the graph minor theorem in a series of twenty papers published 1983–2004.
Further reading
- Reinhard Diestel, Graph Theory (5th edition 2017) — rigorous and complete; chapters 2 (matchings), 4 (planarity), 5 (colouring), 7 (extremal) and 9 (Ramsey).
- J. A. Bondy and U. S. R. Murty, Graph Theory with Applications (1976), and Graph Theory (2008).
- Douglas B. West, Introduction to Graph Theory (2nd edition 2001) — the standard undergraduate text.
- Béla Bollobás, Modern Graph Theory (1998).
- Noga Alon and Joel Spencer, The Probabilistic Method (4th edition 2016) — for Erdős's method and random graphs.
- Robin Wilson, Four Colours Suffice (2002) — the history of the four colour problem, for a general reader.
Next steps in the Lumenary: computational complexity (3-colouring and other NP-complete graph problems), the probabilistic method, and extremal and additive combinatorics.