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
- 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.
- Give each node one of m colours so that no two connected nodes share a colour.
- Go through the nodes in order. For each node try colour 1, 2, … in turn.
- 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.
- If no colour is allowed, backtrack: return to the previous node and give it its next colour.
- If the very first node runs out of colours, the graph cannot be coloured with m colours.
Watch it run
Loading animation…