Learn / Recursion and backtracking

M-colouring

Colour the vertices of a graph one at a time, giving each a colour that none of its already-coloured neighbours has. If a vertex has no allowed colour, undo the previous choice. The smallest number of colours that works is the chromatic number. Graphs are explained on the Structures page.

How to recognise it

  • Neighbouring items must get different labels (colours, time slots, frequencies).
  • The question asks whether m labels are enough, or for the fewest that work.
  • The graph is small (about 20 vertices or fewer).

The idea in one picture

Go through the vertices in order with a box of m crayons. Give each vertex the first crayon none of its coloured neighbours used. If every crayon clashes, go back to the previous vertex and switch its crayon.

See graphs on the Structures page for what vertices, edges and adjacency lists are.

Template

function colour(v):
    if v == n: return true
    for c in 1..m:
        if no neighbour of v has colour c:
            col[v] = c
            if colour(v + 1): return true
            col[v] = 0
    return false

For the chromatic number, run this for m = 1, 2, 3, … and stop at the first m that succeeds.

Common mistakes

  • Checking every vertex instead of only neighbours.
  • Forgetting that edges are undirected, so each edge must go into both adjacency lists.
  • Not undoing col[v], which leaves a stale colour that blocks later choices.

Problems

0 of 2 solved

Check yourself

When choosing a colour for vertex v, which vertices must you check?

A triangle (three vertices, all connected) needs how many colours?

Why is the search exponential in the worst case?