M Coloring Problem
Pattern: M-colouring
Colour the vertices one at a time with colours 1 to m, giving each a colour that none of its already-coloured neighbours has. If a vertex has no allowed colour, undo the previous choice. Success means m colours are enough.
The problem
Given an undirected graph with n vertices (numbered from 0), its edges, and a number m, return whether the vertices
can be coloured with at most m colours so that the two ends of every edge differ. For example, a 4-vertex graph with
edges 0-1, 1-2, 2-3, 3-0, 0-2 and m = 3 gives true, and a triangle with m = 2 gives false.
The function name graphColoring(edges, m, n) matches the takeUforward practice page, including the order of its
inputs. Use the link above for the exact statement and limits. Graphs are explained on the Structures page.
Think first
- Which vertices can clash with the one you are colouring?
- What happens when no colour is allowed?
- How do edges become neighbour lists?
Hints
Brute force, and why it fails
Try all mⁿ assignments and check every edge: O(mⁿ × e). Backtracking checks each vertex as it is coloured and stops at
the first clash.
The key insight
Only already-coloured neighbours constrain a vertex. Checking them at the moment of choosing prunes every assignment that would clash later.
Dry run
| m | 2 |
|---|
Three vertices, all joined (a triangle), and m = 2.
The plan
build adjacency lists
function colour(v):
if v == n: return true
for c in 1..m:
if no neighbour of v has colour c:
col[v] = c
if colour(v + 1): return true
col[v] = 0
return false
return colour(0)
Complexity
- Time
O(mⁿ) worst- Space
O(n + e)
Exponential in the worst case, since the problem is NP-complete for m ≥ 3. The lists and the recursion take
O(n + e).
Edge cases
- No edges: true for any
m ≥ 1. m ≥ n: always true.- A complete graph on
nvertices withm = n - 1: false.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public boolean graphColoring(int[][] edges, int m, int n) {
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]); }
return colour(adj, 0, m, new int[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 and try the next colour
}
return false;
}
}C++
class Solution {
public:
bool graphColoring(vector<vector<int>>& edges, int m, int n) {
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]); }
vector<int> col(n, 0);
return colour(adj, 0, m, col);
}
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 and try the next colour
}
return false;
}
};Python
class Solution:
def graphColoring(self, edges: list[list[int]], m: int, n: int) -> bool:
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
col = [0] * n
def colour(v: int) -> 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):
return True
col[v] = 0 # undo and try the next colour
return False
return colour(0)Common mistakes
- Swapping the order of
mandnin the signature. - Checking all vertices instead of neighbours.
- Forgetting to reset a colour when backing up.