TExcelTAD
Home › Discrete Mathematics › Graph Coloring

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 χ(G)\chi(G). 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 χ\chi Why
no edges 1 nothing conflicts
bipartite graph with an edge 2 the two sides
even cycle C2kC_{2k} 2 alternate colors
odd cycle C2k+1C_{2k+1} 3 alternating fails at the end
complete graph KnK_n nn every pair conflicts

Two simple bounds: χ(G)≥ω(G)\chi(G) \ge \omega(G), the size of the largest clique (set of pairwise adjacent vertices), since a clique needs all different colors; and χ(G)≤Δ(G)+1\chi(G) \le \Delta(G) + 1, where Δ\Delta 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 Δ\Delta neighbours, so one of the colors 0,…,Δ0, \ldots, \Delta is always free:

Theorem. Greedy coloring uses at most Δ(G)+1\Delta(G) + 1 colors.

Proof by induction on the number of colored vertices: when vertex vv is colored, its at most Δ\Delta colored neighbours block at most Δ\Delta colors. ■\blacksquare

The result depends on the order. On some graphs a bad order is very wasteful:

python · try it yourself
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 χ(G)\chi(G) exactly is NP-hard (deciding whether χ≤3\chi \le 3 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 χ\chi is the minimum number of exam slots.

python · try it yourself
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 χ≤4\chi \le 4. 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 χ\chi for (a) C5C_5; (b) K4K_4; (c) a star with 6 leaves; (d) the wheel W5W_5 (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 C5C_5 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 χ\chi be smaller?

Answer

At most 6 colors; yes, χ\chi can be much smaller (for example 2 for a star with 5 leaves).

Solution

The theorem gives Δ+1=6\Delta + 1 = 6. It is only an upper bound: a star with 5 leaves has Δ=5\Delta = 5 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
python · try it yourself
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?

  1. 2
  2. 3
  3. 4
  4. depends on its length

Greedy coloring with any vertex order uses at most…

  1. χ(G)\chi(G) colors
  2. Δ(G)+1\Delta(G) + 1 colors
  3. 2 colors
  4. ∣V∣/2\lvert V \rvert / 2 colors

In compiler register allocation, what are the colors?

  1. Variables
  2. Machine registers
  3. Instructions
  4. Basic blocks