Graph ColouringProblem
Pattern: M-colouring
The chromatic number is the fewest colours that let every edge join two different colours. Try m = 1, 2, 3, … and, for each, backtrack over the vertices giving each a colour none of its neighbours has. The first m that succeeds is the answer.
The problem
Given an undirected graph with n vertices (numbered from 0) and a list of edges, return its chromatic number: the
smallest number of colours needed so that the two ends of every edge have different colours. For example, a triangle
needs 3, a 5-cycle needs 3, and a graph with no edges needs 1.
The link above is a GeeksforGeeks article about where graph colouring is used. The function name
chromaticNumber(n, edges) and this exact task are this guide's own. Graphs are explained on the Structures page.
Think first
- How do you check whether
mcolours are enough? - Why try
min increasing order? - What is the most
mcan ever need to be?
Hints
Brute force, and why it fails
Try every assignment of up to n colours: nⁿ. The backtracking check prunes clashes as soon as they appear. The problem
is NP-hard, so no fast exact method is known.
The key insight
"The fewest colours" is a search over m wrapped around a yes/no check. Each check is the M Colouring backtracking.
Dry run
| m | 1 |
|---|
Four vertices with edges 0-1, 1-2, 2-3, 3-0 and 0-2. Try m = 1. Vertex 1 clashes with 0 at once.
The plan
build adjacency lists
for m from 1 to n:
if colour(0, m): return m
function colour(v, m):
if v == n: return true
for c in 1..m:
if no neighbour of v has c:
col[v] = c; if colour(v + 1, m): return true; col[v] = 0
return false
Complexity
- Time
O(n × mⁿ) worst- Space
O(n + e)
Each check can try up to mⁿ assignments. The adjacency lists take O(n + e).
Edge cases
- No edges: 1.
- A complete graph on
nvertices:n. - Two separate edges: 2.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int chromaticNumber(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
for (int m = 1; m <= n; m++) { // the smallest m that works
if (colour(adj, 0, m, new int[n])) return m;
}
return n;
}
private boolean colour(List<List<Integer>> adj, int v, int m, int[] col) {
if (v == col.length) return true; // every vertex has a colour
for (int c = 1; c <= m; c++) {
boolean clash = false;
for (int u : adj.get(v)) if (col[u] == c) { clash = true; break; } // a neighbour already has c
if (clash) continue;
col[v] = c;
if (colour(adj, v + 1, m, col)) return true;
col[v] = 0; // undo
}
return false;
}
}C++
class Solution {
public:
int chromaticNumber(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
for (const vector<int>& e : edges) { adj[e[0]].push_back(e[1]); adj[e[1]].push_back(e[0]); }
for (int m = 1; m <= n; m++) { // the smallest m that works
vector<int> col(n, 0);
if (colour(adj, 0, m, col)) return m;
}
return n;
}
bool colour(vector<vector<int>>& adj, int v, int m, vector<int>& col) {
if (v == static_cast<int>(col.size())) return true; // every vertex has a colour
for (int c = 1; c <= m; c++) {
bool clash = false;
for (int u : adj[v]) if (col[u] == c) { clash = true; break; } // a neighbour already has c
if (clash) continue;
col[v] = c;
if (colour(adj, v + 1, m, col)) return true;
col[v] = 0; // undo
}
return false;
}
};Python
class Solution:
def chromaticNumber(self, n: int, edges: list[list[int]]) -> int:
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
def colour(v: int, m: int, col: list) -> bool:
if v == n:
return True # every vertex has a colour
for c in range(1, m + 1):
if any(col[u] == c for u in adj[v]):
continue # a neighbour already has c
col[v] = c
if colour(v + 1, m, col):
return True
col[v] = 0 # undo
return False
for m in range(1, n + 1): # the smallest m that works
if colour(0, m, [0] * n):
return m
return nCommon mistakes
- Starting from
m = 0. - Reusing the colour array between values of
mwithout clearing it. - Adding each edge in one direction only.