639. Colour the Map

Medium3.5 points estimatedGraphBacktracking3 hints

A map has n regions numbered 0 to n - 1. Each pair [a, b] in edges says that regions a and b share a border. You have m paint colours and must give every region one colour so that regions sharing a border get different colours. Not every colour has to be used.

Return true if the map can be coloured, otherwise false. No region borders itself; a border may be listed more than once.

Example 1

Input:
n = 3, edges = [[0,1],[1,2],[0,2]], m = 2
Output:
false
Explanation:

The three regions all touch each other, so they need three different colours; two are not enough.

Example 2

Input:
n = 3, edges = [[0,1],[1,2],[0,2]], m = 3
Output:
true
Explanation:

Give each region its own colour.

Example 3

Input:
n = 4, edges = [[0,1],[1,2],[2,3],[3,0]], m = 2
Output:
true
Explanation:

Colour regions 0 and 2 with the first colour and regions 1 and 3 with the second.

Constraints

  • 1 ≤ n ≤ 12
  • 0 ≤ edges.length ≤ 66; 0 ≤ a, b < n and a ≠ b
  • 1 ≤ m ≤ 12

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(m^n) in the worst case, much less with pruning
Space
O(n + edges)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…