Problem 436
Graph M-Coloring
Hard · 30 pts · Graph, Backtracking
Problem
Decide whether the nodes of an undirected graph can be coloured with at most M colours so that no edge connects two nodes of the same colour. This is NP-complete in general, but the graph here is small. Backtracking works well: colour the nodes one at a time, try each colour that no already-coloured neighbour uses, and undo a choice when it leads to a dead end.
Input
First line: N, E and M. Next E lines: an edge u v (nodes labelled 1 to N).
Output
Print YES if the graph can be coloured with M colours, otherwise NO.
Constraints
1 <= N <= 12; 0 <= E <= N(N-1)/2; 1 <= M <= N
Example input
4 5 3 1 2 2 3 3 4 4 1 1 3
Example output
YES
Explanation
Nodes 1, 2, 3 and 4 with edges 1-2, 2-3, 3-4, 4-1 and 1-3: nodes 1, 2 and 3 form a triangle, so they need three different colours, and node 4 can reuse node 2's colour. Three colours are enough, so the answer is YES.