Chromatic number

The chromatic number of a graph is the fewest colours that colour its vertices so that adjacent vertices differ. For small graphs you can find it by trying every colouring.

What to build

A program that finds the chromatic number of a small graph.

Requirements

  • Read n and m, then m edges u v of a simple undirected graph on the vertices 1 to n.
  • Print colours: and the smallest k such that the vertices can be given colours 0 to k − 1 with no edge joining two vertices of the same colour.

Input

The first line has n and m. Each of the next m lines has an edge.

Output

One line.

Constraints

1 ≤ n ≤ 6; 0 ≤ m ≤ 15.

Example

Input:

3 3
1 2
2 3
1 3

Output:

colours: 3

Why it works

With k colours there are k to the power n colourings, and one of them is proper exactly when the chromatic number is at most k. Trying k upward therefore finds the minimum. A graph with no edges needs one colour, a graph with an odd cycle needs at least three and the complete graph on n vertices needs n.

Examples

Example 1 · Input
3 3
1 2
2 3
1 3
Expected output
colours: 3
Example 2 · Input
4 4
1 2
2 3
3 4
4 1
Expected output
colours: 2

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Try k = 1, 2, 3, ... and stop at the first k for which a proper colouring exists.

Hint 2

itertools.product(range(k), repeat=n) lists every way to give each vertex one of k colours.

Hint 3

A colouring is proper when no edge has the same colour at both ends.

Solution

Show one correct solution (try it yourself first)
from itertools import product

n, m = map(int, input().split())
edges = [tuple(map(int, input().split())) for _ in range(m)]
answer = n
for k in range(1, n + 1):
    found = False
    for col in product(range(k), repeat=n):
        if all(col[u - 1] != col[v - 1] for u, v in edges):
            found = True
            break
    if found:
        answer = k
        break
print("colours:", answer)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Graphs →