Algorithms · Visualized
M-Coloring Problem
Backtracking
Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.
Given a graph and m colors, assign each vertex a color so that no two adjacent vertices share one. Time: O(mⁿ) average, O(mⁿ) — n vertices, m choices each worst; space: O(n) recursion depth plus the color array.
Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.
M-Coloring Problem
BacktrackingGiven a graph and m colors, assign each vertex a color so that no two adjacent vertices share one. Backtracking colors vertices in order: try color 1..m on the current vertex, skip any color used by an already-colored neighbour, recurse to the next vertex, and backtrack when every color is blocked.
How M-Coloring Problem Works
- Start with vertex 0 and no colors assigned.
- For the current vertex, try each color from 1 to m.
- Check every already-colored neighbour: if any uses this color, reject it.
- If a color survives, assign it and recurse on the next vertex.
- If all vertices are colored, a valid coloring has been found; if a vertex runs out of colors, undo (backtrack) and let an earlier vertex try its next color.
M-Coloring Problem Worked Example
Input: {graph: [[1, 2], [0, 2, 3], [0, 1, 3], [1, 2]], m: 3}
Vertex 0 → c1. Vertex 1 (adjacent to 0) → c2. Vertex 2 (adjacent to both) → c3. Vertex 3 (adjacent to 1 and 2): c1 free → assign. Result: [c1, c2, c3, c1] — only 3 colors needed for this cycle-plus-chord graph.
| vertex | color | neighbours | |
|---|---|---|---|
| 0 | 0 | — | 1, 2 |
| 1 | 1 | — | 0, 2, 3 |
| 2 | 2 | — | 0, 1, 3 |
| 3 | 3 | — | 1, 2 |
def m_coloring(graph, m):
n = len(graph)
color = [0] * n
def safe(v, c):
return all(color[nb] != c for nb in graph[v])
def rec(v):
if v == n:
return True
for c in range(1, m + 1):
if safe(v, c):
color[v] = c
if rec(v + 1):
return True
color[v] = 0 # backtrack
return False
return color if rec(0) else NoneBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
M-Coloring Problem Time & Space Complexity
When to Use M-Coloring Problem
- Timetabling / exam scheduling where clashing events need different slots.
- Register allocation in compilers (variables that are live simultaneously get different registers).
- Map coloring — the classic application that gave the problem its name.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.