GeeksforGeeks Medium

M-Coloring Problem

M-Coloring Problem is a GFG problem (Medium). You get an undirected graph with v vertices, numbered from 0, as a list of edges, and a number m.

  • Return true if every vertex can get one of m colors so that no edge joins two vertices of the same color, and false otherwise.

The graph has at most 10 vertices. That small size is what makes trying colors one vertex at a time fast enough, even though the worst case is exponential.

Constraints
  • 1 <= v <= 10
  • 1 <= E = edges.size() <= v * (v - 1) / 2
  • 0 <= edges[i][j] <= v - 1
  • 1 <= m <= v
backtrackinggraph
Open on GeeksforGeeks ↗
02

Intuition

No formula answers this (it is NP-complete once m is 3 or more), so the solution is a careful search. Color the vertices in order 0, 1, 2, …, try colors 1 to m at each one, and back up the moment a vertex has no legal color.

  • Check only colored neighbors: a neighbor with no color yet cannot clash; it is checked on its own turn.
  • Back up on a dead end: if nothing fits a vertex, an earlier choice caused it, so return to the previous vertex and give it its next color.
  • Stop at the first success: the answer is yes or no, so one complete coloring ends the search.
How to spot this pattern

"Assign each item one of a few labels so no two related items share one" is constraint backtracking: place, check, recurse, undo. N-Queens and Sudoku have the same shape with a different check.

03

Approach

Try it first

Before reading on: when you give a vertex a color, which other vertices does that choice restrict, and what has to be undone if the choice leads nowhere? Aim for a search that drops a branch as soon as it clashes.

1

Build neighbor lists

Turn edges into adj, adding every edge in both directions because the graph is undirected. Checking a color then means scanning one vertex's neighbors instead of all v vertices.

2

Try each color at the current vertex

For node, go through colors 1 to m. A color is allowed when no neighbor already has it. Uncolored neighbors hold 0, which never matches a real color.

3

Paint, go deeper, erase on failure

Set color[node] = c and call place(node + 1). If it returns true, pass true straight up. If not, set color[node] back to 0 and try the next color.

4

Decide at the two ends

Reaching node == v means every vertex has a legal color, so return true. Running out of colors at a vertex returns false to the caller, which then tries its own next color.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def graphColoring(self, v, edges, m):
▶3 adj = [[] for _ in range(v)]
▶4 for a, b in edges:
▶5 adj[a].append(b)
▶6 adj[b].append(a)
▶7 color = [0] * v
▶8 
▶9 def place(node):
▶10 if node == v:
▶11 return True
▶12 for c in range(1, m + 1):
▶13 if all(color[nb] != c for nb in adj[node]):
▶14 color[node] = c
▶15 if place(node + 1):
▶16 return True
▶17 color[node] = 0
▶18 return False
▶19 
▶20 return place(0)
0123colors123color arrayno vertex colored yet, 3 colors to use
colors[0, 0, 0, 0]0 means none yet
Vertices are colored in order 0, 1, 2, … Each one tries colors 1 to 3, and a color is refused if a neighbor already has it.
0123colors for vertex 01fits23color array1vertex 0 gets color 1 → go to vertex 1
colors[1, 0, 0, 0]0 means none yet
No colored neighbor of 0 uses color 1; its uncolored neighbors do not count yet, they are checked on their own turn. Paint it and move on to vertex 1.
0123colors for vertex 11clash23color array1vertex 1: color 1 clashes with vertex 0
colors[1, 0, 0, 0]0 means none yet
Vertex 0 is a neighbor of 1 and already has color 1, so 1 cannot use it. Move on to the next color.
0123colors for vertex 11tried2fits3color array12vertex 1 gets color 2 → go to vertex 2
colors[1, 2, 0, 0]0 means none yet
No colored neighbor of 1 uses color 2. Paint it and move on to vertex 2.
0123colors for vertex 21clash23color array12vertex 2: color 1 clashes with vertex 0
colors[1, 2, 0, 0]0 means none yet
Vertex 0 is a neighbor of 2 and already has color 1, so 2 cannot use it. Move on to the next color.
0123colors for vertex 21tried2fits3color array122vertex 2 gets color 2 → go to vertex 3
colors[1, 2, 2, 0]0 means none yet
No colored neighbor of 2 uses color 2. Paint it and move on to vertex 3.
0123colors for vertex 31clash23color array122vertex 3: color 1 clashes with vertex 0
colors[1, 2, 2, 0]0 means none yet
Vertex 0 is a neighbor of 3 and already has color 1, so 3 cannot use it. Move on to the next color.
0123colors for vertex 31tried2clash3color array122vertex 3: color 2 clashes with vertex 1
colors[1, 2, 2, 0]0 means none yet
Vertex 1 is a neighbor of 3 and already has color 2, so 3 cannot use it. Move on to the next color.
0123colors for vertex 31tried2tried3fitscolor array1223vertex 3 gets color 3
colors[1, 2, 2, 3]0 means none yet
No colored neighbor of 3 uses color 3. Paint it and move on.
0123colors123color array1223all 4 vertices colored → true
answertrue
The search has moved past the last vertex, so every vertex has a color and no edge joins two of the same color. Return true at once; there is no need to look for other colorings.
05

Common pitfalls

Adding each edge in one direction only

✗ Wrong
for a, b in edges:
    adj[a].append(b)
✓ Right
for a, b in edges:
    adj[a].append(b)
    adj[b].append(a)

Vertex 1 then never sees its neighbor 0. On the triangle [[0, 1], [1, 2], [0, 2]] with m = 2 every vertex gets color 1 and the code returns true; the answer is false.

Returning true without checking the rest

✗ Wrong
color[node] = c
place(node + 1)
return True
✓ Right
color[node] = c
if place(node + 1):
    return True
color[node] = 0

Success needs every later vertex colored too. On the same triangle with m = 2, vertex 2 finds no color, but the true from vertex 0 is already on its way up.

06

Edge cases

m = 1 and at least one edge

Both ends of that edge would need color 1, so the search fails at the second one and returns false.

m is more than the largest number of neighbors

A vertex always has a color its neighbors are not using, so the search never backs up and returns true on the first pass.

07

Complexity

Time
O(m^v · v)
Space
O(v + E)
Up to m choices at each of the v vertices, and each check scans one vertex's neighbors. Clashes cut most branches early, so real runs on 10 vertices are far smaller. Space is the neighbor lists, the color array and v levels of recursion.
08

M-Coloring Problem FAQ

How is the m coloring problem related to the chromatic number?

This problem fixes m and asks yes or no. The chromatic number is the smallest m for which the answer is yes, so you can find it by running this check for m = 1, 2, 3, … and stopping at the first true.

Is m = 2 a special case?

Yes. Two colors work exactly when the graph is bipartite, and a BFS that gives each neighbor the opposite color checks that in O(v + E) with no backing up.

Does the order of the vertices matter?

Not for the answer, only for speed. Coloring the vertices with the most neighbors first tends to reach dead ends sooner, which cuts more branches.