Graph Coloring
A coloring of a graph gives each vertex a color so that adjacent vertices get different colors. The smallest number of colors that works is the chromatic number . Coloring models conflicts: exams that share a student cannot be at the same time, variables that are live at the same time cannot share a CPU register, neighbouring cell towers need different frequencies.
Examples
| Graph | Why | |
|---|---|---|
| no edges | 1 | nothing conflicts |
| bipartite graph with an edge | 2 | the two sides |
| even cycle | 2 | alternate colors |
| odd cycle | 3 | alternating fails at the end |
| complete graph | every pair conflicts |
Two simple bounds: , the size of the largest clique (set of pairwise adjacent vertices), since a clique needs all different colors; and , where is the maximum degree.
Greedy coloring
Take the vertices in some order and give each the smallest color not used by its already-colored neighbours. A vertex has at most neighbours, so one of the colors is always free:
Theorem. Greedy coloring uses at most colors.
Proof by induction on the number of colored vertices: when vertex is colored, its at most colored neighbours block at most colors.
The result depends on the order. On some graphs a bad order is very wasteful:
def greedy(order, adj):
color = {}
for v in order:
used = {color[w] for w in adj[v] if w in color}
color[v] = next(c for c in range(len(adj)) if c not in used)
return color
# "crown" graph: a_i adjacent to b_j for i != j (it is bipartite, so 2 colors suffice)
n = 5
adj = {f"a{i}": [f"b{j}" for j in range(n) if j != i] for i in range(n)}
adj.update({f"b{j}": [f"a{i}" for i in range(n) if i != j] for j in range(n)})
bad = [x for i in range(n) for x in (f"a{i}", f"b{i}")] # a0, b0, a1, b1, ...
good = [f"a{i}" for i in range(n)] + [f"b{i}" for i in range(n)] # one side first
print("interleaved order uses", len(set(greedy(bad, adj).values())), "colors")
print("side-by-side order uses", len(set(greedy(good, adj).values())), "colors")interleaved order uses 5 colors
side-by-side order uses 2 colors
Finding exactly is NP-hard (deciding whether is NP-complete; see the SAT encoding in Satisfiability). In practice, heuristics such as "largest degree first" (Welsh–Powell) or DSatur work well.
Exam scheduling
Courses are vertices; two courses are adjacent if some student takes both. A coloring is an exam timetable, and is the minimum number of exam slots.
students = {
"ann": ["math", "cs", "art"],
"bob": ["math", "phys"],
"cid": ["cs", "phys", "chem"],
"dee": ["art", "chem"],
"eli": ["bio", "math"],
}
courses = sorted({c for cs in students.values() for c in cs})
adj = {c: set() for c in courses}
for cs in students.values():
for a in cs:
adj[a] |= set(cs) - {a}
order = sorted(courses, key=lambda c: -len(adj[c])) # largest degree first
slot = {}
for c in order:
used = {slot[d] for d in adj[c] if d in slot}
slot[c] = min(s for s in range(len(courses)) if s not in used)
for s in sorted(set(slot.values())):
print("slot", s, ":", sorted(c for c in slot if slot[c] == s))slot 0 : ['bio', 'cs']
slot 1 : ['chem', 'math']
slot 2 : ['art', 'phys']
Three slots are optimal here: math, cs and art are pairwise adjacent (ann takes all three), a clique of size 3.
The Four Color Theorem
Every map drawn in the plane can be colored with 4 colors so that neighbouring countries differ. In graph terms, every planar graph has . It was proved in 1976 by Appel and Haken with a computer check of nearly 2000 configurations, the first major theorem proved with essential computer help. Five colors are much easier to prove (Planar Graphs).
In software
Compilers do register allocation by coloring the interference graph of variables (two variables interfere if they are live at the same time), with colors = registers. Sudoku is a 9-coloring of an 81-vertex graph with some colors fixed. Frequency assignment, task scheduling with conflicts and map rendering all reduce to coloring.
Exercises
Exercise 1: Chromatic numbers
Find for (a) ; (b) ; (c) a star with 6 leaves; (d) the wheel (a 5-cycle plus a centre joined to all).
Answer
(a) 3; (b) 4; (c) 2; (d) 4.
Solution
(a) Odd cycle. (b) Complete graph. (c) A star is bipartite. (d) The rim needs 3 colors and the centre is adjacent to all rim vertices, so it needs a 4th.
Exercise 2: Greedy bound
A graph has maximum degree 5. What does greedy coloring guarantee? Can be smaller?
Answer
At most 6 colors; yes, can be much smaller (for example 2 for a star with 5 leaves).
Solution
The theorem gives . It is only an upper bound: a star with 5 leaves has but is bipartite.
Exercise 3: Lower bound by a clique (code)
For the exam graph above, find the largest clique by brute force to confirm 3 slots are needed.
Answer
The largest clique has size 3 (for example art, chem, cs; also art, cs, math).
Solution
from itertools import combinations
students = [["math", "cs", "art"], ["math", "phys"], ["cs", "phys", "chem"], ["art", "chem"], ["bio", "math"]]
edges = {frozenset(p) for cs in students for p in combinations(cs, 2)}
courses = sorted({c for cs in students for c in cs})
best = max((S for k in range(1, 5) for S in combinations(courses, k)
if all(frozenset(p) in edges for p in combinations(S, 2))), key=len)
print(len(best), best)3 ('art', 'chem', 'cs')
Test yourself
What is the chromatic number of an odd cycle?
- 2
- 3
- 4
- depends on its length
Greedy coloring with any vertex order uses at most…
- colors
- colors
- 2 colors
- colors
In compiler register allocation, what are the colors?
- Variables
- Machine registers
- Instructions
- Basic blocks