Skip to content
StackDecode
BacktrackingAnimated

Graph Coloring

Give adjacent nodes different colours using at most m colours.

Time

O(mⁿ)

Extra space

O(n)

Use it for

Scheduling and register allocation.

How it works

  1. Give each node one of m colours so that no two connected nodes share a colour.
  2. Go through the nodes in order. For each node try colour 1, 2, … in turn.
  3. A colour is allowed only if none of its already-coloured neighbours uses it. Take the first allowed colour and move to the next node.
  4. If no colour is allowed, backtrack: return to the previous node and give it its next colour.
  5. If the very first node runs out of colours, the graph cannot be coloured with m colours.

Watch it run

Loading animation…