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
- 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…