Skip to content
StackDecode
BacktrackingAnimated

M-Coloring Problem

Decide whether a graph can be coloured with m colours.

Time

O(mⁿ)

Extra space

O(n)

Use it for

Map colouring.

How it works

  1. The m-colouring problem asks: can the graph be coloured with at most m colours so adjacent nodes differ? It is solved exactly like graph colouring.
  2. Give each node one of m colours so that no two connected nodes share a colour.
  3. Go through the nodes in order. For each node try colour 1, 2, … in turn.
  4. 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.
  5. If no colour is allowed, backtrack: return to the previous node and give it its next colour.
  6. If the very first node runs out of colours, the graph cannot be coloured with m colours.

Watch it run

Loading animation…