Given an undirected graph, check if it is k–colorable or not and print all possible configurations of assignment of colors to its vertices.

The vertex coloring is a way of coloring the vertices of a graph such that no two adjacent vertices share the same color. A coloring using at most k colors is called a (proper) k–coloring, and a graph that can be assigned a (proper) k–coloring is k–colorable.

For example, consider the following graph,

 
Graph coloring

It can be 3–colored in several ways:

 
Graph Coloring – Option 1 Graph Coloring – Option 2Graph Coloring – Option 3

Please note that we can’t color the above graph using two colors, i.e., it’s not 2–colorable.

Practice this problem

We can use backtracking to solve this problem. The idea is to try all possible combinations of colors for the first vertex in the graph and recursively explore the remaining vertices to check if they will lead to the solution or not. If the current configuration doesn’t result in a solution, backtrack. Note that we assign any color to a vertex only if its adjacent vertices share the different colors.

The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
BLUE    GREEN   BLUE    RED     RED     GREEN
BLUE    GREEN   GREEN   BLUE    RED     GREEN
BLUE    GREEN   GREEN   RED     RED     GREEN
BLUE    RED     BLUE    GREEN   GREEN   RED
BLUE    RED     RED     BLUE    GREEN   RED
BLUE    RED     RED     GREEN   GREEN   RED
GREEN   BLUE    BLUE    GREEN   RED     BLUE
GREEN   BLUE    BLUE    RED     RED     BLUE
GREEN   BLUE    GREEN   RED     RED     BLUE
GREEN   RED     GREEN   BLUE    BLUE    RED
GREEN   RED     RED     BLUE    BLUE    RED
GREEN   RED     RED     GREEN   BLUE    RED
RED     BLUE    BLUE    GREEN   GREEN   BLUE
RED     BLUE    BLUE    RED     GREEN   BLUE
RED     BLUE    RED     GREEN   GREEN   BLUE
RED     GREEN   GREEN   BLUE    BLUE    GREEN
RED     GREEN   GREEN   RED     BLUE    GREEN
RED     GREEN   RED     BLUE    BLUE    GREEN

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack).