Search and backtracking · 15 / 15 Exercise Hard

Color a map

Objective

Create a Python program that colors a map (a graph) with k colors so that two neighboring regions never have the same color, using backtracking.

Instructions

  • The first line contains three integers n, m and k: number of regions (1 to 8, numbered from 1), number of borders and number of colors (numbered from 1). The next m lines each contain two neighboring regions a b.
  • Assign colors to the regions in order (1, 2, 3...). For each region try the colors from 1 to k in order and keep the first one that its already colored neighbors do not use. If with that color the rest cannot be completed, undo the choice (delete the assignment) and try the next one.
  • Show Colors: c1 c2 ... cn with the color of each region (from 1 to n), or No solution if it is not possible.
Input
4 5 3
1 2
1 3
2 3
2 4
3 4
Output
Colors: 1 2 3 1

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise