 GeeksforGeeks App
Open App Browser
Continue

# m Coloring Problem

Given an undirected graph and a number m, determine if the graph can be colored with at most m colors such that no two adjacent vertices of the graph are colored with the same color

Note: Here coloring of a graph means the assignment of colors to all vertices

Following is an example of a graph that can be colored with 3 different colors: Examples:

Input:  graph = {0, 1, 1, 1},
{1, 0, 1, 0},
{1, 1, 0, 1},
{1, 0, 1, 0}
Output: Solution Exists: Following are the assigned colors: 1  2  3  2
Explanation: By coloring the vertices
vertices does not have same colors

Input: graph = {1, 1, 1, 1},
{1, 1, 1, 1},
{1, 1, 1, 1},
{1, 1, 1, 1}

Output: Solution does not exist
Explanation: No solution exits

## We strongly recommend that you click here and practice it, before moving on to the solution.

Naive Approach: To solve the problem follow the below idea:

Generate all possible configurations of colors. Since each node can be colored using any of the m available colors, the total number of color configurations possible is mV. After generating a configuration of color, check if the adjacent vertices have the same color or not. If the conditions are met, print the combination and break the loop

Follow the given steps to solve the problem:

• Create a recursive function that takes the current index, number of vertices and output color array
• If the current index is equal to number of vertices. Check if the output color configuration is safe, i.e check if the adjacent vertices do not have same color. If the conditions are met, print the configuration and break
• Assign a color to a vertex (1 to m)
• For every assigned color recursively call the function with next index and number of vertices
• If any recursive function returns true break the loop and returns true.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Number of vertices in the graph``#define V 4` `void` `printSolution(``int` `color[]);` `// check if the colored``// graph is safe or not``bool` `isSafe(``bool` `graph[V][V], ``int` `color[])``{``    ``// check for every edge``    ``for` `(``int` `i = 0; i < V; i++)``        ``for` `(``int` `j = i + 1; j < V; j++)``            ``if` `(graph[i][j] && color[j] == color[i])``                ``return` `false``;``    ``return` `true``;``}` `/* This function solves the m Coloring``problem using recursion. It returns``false if the m colours cannot be assigned,``otherwise, return true and prints``assignments of colours to all vertices.``Please note that there may be more than``one solutions, this function prints one``of the feasible solutions.*/``bool` `graphColoring(``bool` `graph[V][V], ``int` `m, ``int` `i,``                   ``int` `color[V])``{``    ``// if current index reached end``    ``if` `(i == V) {` `        ``// if coloring is safe``        ``if` `(isSafe(graph, color)) {` `            ``// Print the solution``            ``printSolution(color);``            ``return` `true``;``        ``}``        ``return` `false``;``    ``}` `    ``// Assign each color from 1 to m``    ``for` `(``int` `j = 1; j <= m; j++) {``        ``color[i] = j;` `        ``// Recur of the rest vertices``        ``if` `(graphColoring(graph, m, i + 1, color))``            ``return` `true``;` `        ``color[i] = 0;``    ``}` `    ``return` `false``;``}` `/* A utility function to print solution */``void` `printSolution(``int` `color[])``{``    ``cout << ``"Solution Exists:"``            ``" Following are the assigned colors \n"``;``    ``for` `(``int` `i = 0; i < V; i++)``        ``cout << ``"  "` `<< color[i];``    ``cout << ``"\n"``;``}` `// Driver code``int` `main()``{``    ``/* Create following graph and``    ``test whether it is 3 colorable``    ``(3)---(2)``    ``| / |``    ``| / |``    ``| / |``    ``(0)---(1)``    ``*/``    ``bool` `graph[V][V] = {``        ``{ 0, 1, 1, 1 },``        ``{ 1, 0, 1, 0 },``        ``{ 1, 1, 0, 1 },``        ``{ 1, 0, 1, 0 },``    ``};``    ``int` `m = 3; ``// Number of colors` `    ``// Initialize all color values as 0.``    ``// This initialization is needed``    ``// correct functioning of isSafe()``    ``int` `color[V];``    ``for` `(``int` `i = 0; i < V; i++)``        ``color[i] = 0;` `    ``// Function call``    ``if` `(!graphColoring(graph, m, 0, color))``        ``cout << ``"Solution does not exist"``;` `    ``return` `0;``}` `// This code is contributed by shivanisinghss2110`

## C

 `// C program for the above approach` `#include ``#include ` `// Number of vertices in the graph``#define V 4` `void` `printSolution(``int` `color[]);` `// check if the colored``// graph is safe or not``bool` `isSafe(``bool` `graph[V][V], ``int` `color[])``{``    ``// check for every edge``    ``for` `(``int` `i = 0; i < V; i++)``        ``for` `(``int` `j = i + 1; j < V; j++)``            ``if` `(graph[i][j] && color[j] == color[i])``                ``return` `false``;``    ``return` `true``;``}` `/* This function solves the m Coloring``   ``problem using recursion. It returns``  ``false if the m colours cannot be assigned,``  ``otherwise, return true and prints``  ``assignments of colours to all vertices.``  ``Please note that there may be more than``  ``one solutions, this function prints one``  ``of the feasible solutions.*/``bool` `graphColoring(``bool` `graph[V][V], ``int` `m, ``int` `i,``                   ``int` `color[V])``{``    ``// if current index reached end``    ``if` `(i == V) {``        ``// if coloring is safe``        ``if` `(isSafe(graph, color)) {``            ``// Print the solution``            ``printSolution(color);``            ``return` `true``;``        ``}``        ``return` `false``;``    ``}` `    ``// Assign each color from 1 to m``    ``for` `(``int` `j = 1; j <= m; j++) {``        ``color[i] = j;` `        ``// Recur of the rest vertices``        ``if` `(graphColoring(graph, m, i + 1, color))``            ``return` `true``;` `        ``color[i] = 0;``    ``}` `    ``return` `false``;``}` `/* A utility function to print solution */``void` `printSolution(``int` `color[])``{``    ``printf``(``"Solution Exists:"``           ``" Following are the assigned colors \n"``);``    ``for` `(``int` `i = 0; i < V; i++)``        ``printf``(``" %d "``, color[i]);``    ``printf``(``"\n"``);``}` `// Driver code``int` `main()``{``    ``/* Create following graph and``       ``test whether it is 3 colorable``      ``(3)---(2)``       ``|   / |``       ``|  /  |``       ``| /   |``      ``(0)---(1)``    ``*/``    ``bool` `graph[V][V] = {``        ``{ 0, 1, 1, 1 },``        ``{ 1, 0, 1, 0 },``        ``{ 1, 1, 0, 1 },``        ``{ 1, 0, 1, 0 },``    ``};``    ``int` `m = 3; ``// Number of colors` `    ``// Initialize all color values as 0.``    ``// This initialization is needed``    ``// correct functioning of isSafe()``    ``int` `color[V];``    ``for` `(``int` `i = 0; i < V; i++)``        ``color[i] = 0;` `    ``// Function call``    ``if` `(!graphColoring(graph, m, 0, color))``        ``printf``(``"Solution does not exist"``);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach` `public` `class` `GFG {` `    ``// Number of vertices in the graph``    ``static` `int` `V = ``4``;` `    ``/* A utility function to print solution */``    ``static` `void` `printSolution(``int``[] color)``    ``{``        ``System.out.println(``            ``"Solution Exists:"``            ``+ ``" Following are the assigned colors "``);``        ``for` `(``int` `i = ``0``; i < V; i++)``            ``System.out.print(``"  "` `+ color[i]);``        ``System.out.println();``    ``}` `    ``// check if the colored``    ``// graph is safe or not``    ``static` `boolean` `isSafe(``boolean``[][] graph, ``int``[] color)``    ``{``        ``// check for every edge``        ``for` `(``int` `i = ``0``; i < V; i++)``            ``for` `(``int` `j = i + ``1``; j < V; j++)``                ``if` `(graph[i][j] && color[j] == color[i])``                    ``return` `false``;``        ``return` `true``;``    ``}` `    ``/* This function solves the m Coloring``      ``problem using recursion. It returns``      ``false if the m colours cannot be assigned,``      ``otherwise, return true and prints``      ``assignments of colours to all vertices.``      ``Please note that there may be more than``      ``one solutions, this function prints one``      ``of the feasible solutions.*/``    ``static` `boolean` `graphColoring(``boolean``[][] graph, ``int` `m,``                                 ``int` `i, ``int``[] color)``    ``{``        ``// if current index reached end``        ``if` `(i == V) {` `            ``// if coloring is safe``            ``if` `(isSafe(graph, color)) {` `                ``// Print the solution``                ``printSolution(color);``                ``return` `true``;``            ``}``            ``return` `false``;``        ``}` `        ``// Assign each color from 1 to m``        ``for` `(``int` `j = ``1``; j <= m; j++) {``            ``color[i] = j;` `            ``// Recur of the rest vertices``            ``if` `(graphColoring(graph, m, i + ``1``, color))``                ``return` `true``;``            ``color[i] = ``0``;``        ``}``        ``return` `false``;``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{` `        ``/* Create following graph and``            ``test whether it is 3 colorable``            ``(3)---(2)``            ``| / |``            ``| / |``            ``| / |``            ``(0)---(1)``            ``*/``        ``boolean``[][] graph = {``            ``{ ``false``, ``true``, ``true``, ``true` `},``            ``{ ``true``, ``false``, ``true``, ``false` `},``            ``{ ``true``, ``true``, ``false``, ``true` `},``            ``{ ``true``, ``false``, ``true``, ``false` `},``        ``};``        ``int` `m = ``3``; ``// Number of colors` `        ``// Initialize all color values as 0.``        ``// This initialization is needed``        ``// correct functioning of isSafe()``        ``int``[] color = ``new` `int``[V];``        ``for` `(``int` `i = ``0``; i < V; i++)``            ``color[i] = ``0``;` `        ``// Function call``        ``if` `(!graphColoring(graph, m, ``0``, color))``            ``System.out.println(``"Solution does not exist"``);``    ``}``}` `// This code is contributed by divyeh072019.`

## Python3

 `# Python3 program for the above approach` `# Number of vertices in the graph``# define 4 4` `# check if the colored``# graph is safe or not`  `def` `isSafe(graph, color):` `    ``# check for every edge``    ``for` `i ``in` `range``(``4``):``        ``for` `j ``in` `range``(i ``+` `1``, ``4``):``            ``if` `(graph[i][j] ``and` `color[j] ``=``=` `color[i]):``                ``return` `False``    ``return` `True` `# /* This function solves the m Coloring``# problem using recursion. It returns``# false if the m colours cannot be assigned,``# otherwise, return true and prints``# assignments of colours to all vertices.``# Please note that there may be more than``# one solutions, this function prints one``# of the feasible solutions.*/`  `def` `graphColoring(graph, m, i, color):` `    ``# if current index reached end``    ``if` `(i ``=``=` `4``):` `        ``# if coloring is safe``        ``if` `(isSafe(graph, color)):` `            ``# Print the solution``            ``printSolution(color)``            ``return` `True``        ``return` `False` `    ``# Assign each color from 1 to m``    ``for` `j ``in` `range``(``1``, m ``+` `1``):``        ``color[i] ``=` `j` `        ``# Recur of the rest vertices``        ``if` `(graphColoring(graph, m, i ``+` `1``, color)):``            ``return` `True``        ``color[i] ``=` `0``    ``return` `False` `# /* A utility function to print solution */`  `def` `printSolution(color):``    ``print``(``"Solution Exists:"` `" Following are the assigned colors "``)``    ``for` `i ``in` `range``(``4``):``        ``print``(color[i], end``=``" "``)`  `# Driver code``if` `__name__ ``=``=` `'__main__'``:` `    ``# /* Create following graph and``    ``# test whether it is 3 colorable``    ``# (3)---(2)``    ``# | / |``    ``# | / |``    ``# | / |``    ``# (0)---(1)``    ``# */``    ``graph ``=` `[``        ``[``0``, ``1``, ``1``, ``1``],``        ``[``1``, ``0``, ``1``, ``0``],``        ``[``1``, ``1``, ``0``, ``1``],``        ``[``1``, ``0``, ``1``, ``0``],``    ``]``    ``m ``=` `3`  `# Number of colors` `    ``# Initialize all color values as 0.``    ``# This initialization is needed``    ``# correct functioning of isSafe()``    ``color ``=` `[``0` `for` `i ``in` `range``(``4``)]` `    ``# Function call``    ``if` `(``not` `graphColoring(graph, m, ``0``, color)):``        ``print``(``"Solution does not exist"``)` `# This code is contributed by mohit kumar 29`

## C#

 `// C# program for the above approach` `using` `System;``class` `GFG {` `    ``// Number of vertices in the graph``    ``static` `int` `V = 4;` `    ``/* A utility function to print solution */``    ``static` `void` `printSolution(``int``[] color)``    ``{``        ``Console.WriteLine(``            ``"Solution Exists:"``            ``+ ``" Following are the assigned colors "``);``        ``for` `(``int` `i = 0; i < V; i++)``            ``Console.Write(``"  "` `+ color[i]);``        ``Console.WriteLine();``    ``}` `    ``// check if the colored``    ``// graph is safe or not``    ``static` `bool` `isSafe(``bool``[, ] graph, ``int``[] color)``    ``{``        ``// check for every edge``        ``for` `(``int` `i = 0; i < V; i++)``            ``for` `(``int` `j = i + 1; j < V; j++)``                ``if` `(graph[i, j] && color[j] == color[i])``                    ``return` `false``;``        ``return` `true``;``    ``}` `    ``/* This function solves the m Coloring``    ``problem using recursion. It returns``    ``false if the m colours cannot be assigned,``    ``otherwise, return true and prints``    ``assignments of colours to all vertices.``    ``Please note that there may be more than``    ``one solutions, this function prints one``    ``of the feasible solutions.*/``    ``static` `bool` `graphColoring(``bool``[, ] graph, ``int` `m, ``int` `i,``                              ``int``[] color)``    ``{``        ``// if current index reached end``        ``if` `(i == V) {` `            ``// if coloring is safe``            ``if` `(isSafe(graph, color)) {` `                ``// Print the solution``                ``printSolution(color);``                ``return` `true``;``            ``}``            ``return` `false``;``        ``}` `        ``// Assign each color from 1 to m``        ``for` `(``int` `j = 1; j <= m; j++) {``            ``color[i] = j;` `            ``// Recur of the rest vertices``            ``if` `(graphColoring(graph, m, i + 1, color))``                ``return` `true``;` `            ``color[i] = 0;``        ``}` `        ``return` `false``;``    ``}` `    ``// Driver code``    ``static` `void` `Main()``    ``{``        ``/* Create following graph and``        ``test whether it is 3 colorable``        ``(3)---(2)``        ``| / |``        ``| / |``        ``| / |``        ``(0)---(1)``        ``*/``        ``bool``[, ] graph = {``            ``{ ``false``, ``true``, ``true``, ``true` `},``            ``{ ``true``, ``false``, ``true``, ``false` `},``            ``{ ``true``, ``true``, ``false``, ``true` `},``            ``{ ``true``, ``false``, ``true``, ``false` `},``        ``};``        ``int` `m = 3; ``// Number of colors` `        ``// Initialize all color values as 0.``        ``// This initialization is needed``        ``// correct functioning of isSafe()``        ``int``[] color = ``new` `int``[V];``        ``for` `(``int` `i = 0; i < V; i++)``            ``color[i] = 0;` `        ``// Function call``        ``if` `(!graphColoring(graph, m, 0, color))``            ``Console.WriteLine(``"Solution does not exist"``);``    ``}``}` `// this code is contributed by divyeshrabadiya07.`

## Javascript

 ``

Output

```Solution Exists: Following are the assigned colors
1  2  3  2
```

Time Complexity: O(mV). There is a total O(mV) combination of colors
Auxiliary Space: O(V). Recursive Stack of graph coloring(…) function will require O(V) space.

## m Coloring Problem using Backtracking:

To solve the problem follow the below idea:

The idea is to assign colors one by one to different vertices, starting from vertex 0. Before assigning a color, check for safety by considering already assigned colors to the adjacent vertices i.e check if the adjacent vertices have the same color or not. If there is any color assignment that does not violate the conditions, mark the color assignment as part of the solution. If no assignment of color is possible then backtrack and return false

Follow the given steps to solve the problem:

• Create a recursive function that takes the graph, current index, number of vertices, and output color array.
• If the current index is equal to the number of vertices. Print the color configuration in the output array.
• Assign a color to a vertex (1 to m).
• For every assigned color, check if the configuration is safe, (i.e. check if the adjacent vertices do not have the same color) recursively call the function with the next index and number of vertices
• If any recursive function returns true break the loop and return true
• If no recursive function returns true then return false

Below is the implementation of the above approach:

## C++

 `// C++ program for solution of M``// Coloring problem using backtracking` `#include ``using` `namespace` `std;` `// Number of vertices in the graph``#define V 4` `void` `printSolution(``int` `color[]);` `/* A utility function to check if``   ``the current color assignment``   ``is safe for vertex v i.e. checks``   ``whether the edge exists or not``   ``(i.e, graph[v][i]==1). If exist``   ``then checks whether the color to``   ``be filled in the new vertex(c is``   ``sent in the parameter) is already``   ``used by its adjacent``   ``vertices(i-->adj vertices) or``   ``not (i.e, color[i]==c) */``bool` `isSafe(``int` `v, ``bool` `graph[V][V], ``int` `color[], ``int` `c)``{``    ``for` `(``int` `i = 0; i < V; i++)``        ``if` `(graph[v][i] && c == color[i])``            ``return` `false``;` `    ``return` `true``;``}` `/* A recursive utility function``to solve m coloring problem */``bool` `graphColoringUtil(``bool` `graph[V][V], ``int` `m, ``int` `color[],``                       ``int` `v)``{` `    ``/* base case: If all vertices are``       ``assigned a color then return true */``    ``if` `(v == V)``        ``return` `true``;` `    ``/* Consider this vertex v and``       ``try different colors */``    ``for` `(``int` `c = 1; c <= m; c++) {` `        ``/* Check if assignment of color``           ``c to v is fine*/``        ``if` `(isSafe(v, graph, color, c)) {``            ``color[v] = c;` `            ``/* recur to assign colors to``               ``rest of the vertices */``            ``if` `(graphColoringUtil(graph, m, color, v + 1)``                ``== ``true``)``                ``return` `true``;` `            ``/* If assigning color c doesn't``               ``lead to a solution then remove it */``            ``color[v] = 0;``        ``}``    ``}` `    ``/* If no color can be assigned to``       ``this vertex then return false */``    ``return` `false``;``}` `/* This function solves the m Coloring``   ``problem using Backtracking. It mainly``   ``uses graphColoringUtil() to solve the``   ``problem. It returns false if the m``   ``colors cannot be assigned, otherwise``   ``return true and prints assignments of``   ``colors to all vertices. Please note``   ``that there may be more than one solutions,``   ``this function prints one of the``   ``feasible solutions.*/``bool` `graphColoring(``bool` `graph[V][V], ``int` `m)``{` `    ``// Initialize all color values as 0.``    ``// This initialization is needed``    ``// correct functioning of isSafe()``    ``int` `color[V];``    ``for` `(``int` `i = 0; i < V; i++)``        ``color[i] = 0;` `    ``// Call graphColoringUtil() for vertex 0``    ``if` `(graphColoringUtil(graph, m, color, 0) == ``false``) {``        ``cout << ``"Solution does not exist"``;``        ``return` `false``;``    ``}` `    ``// Print the solution``    ``printSolution(color);``    ``return` `true``;``}` `/* A utility function to print solution */``void` `printSolution(``int` `color[])``{``    ``cout << ``"Solution Exists:"``         ``<< ``" Following are the assigned colors"``         ``<< ``"\n"``;``    ``for` `(``int` `i = 0; i < V; i++)``        ``cout << ``" "` `<< color[i] << ``" "``;` `    ``cout << ``"\n"``;``}` `// Driver code``int` `main()``{` `    ``/* Create following graph and test``       ``whether it is 3 colorable``      ``(3)---(2)``       ``|   / |``       ``|  /  |``       ``| /   |``      ``(0)---(1)``    ``*/``    ``bool` `graph[V][V] = {``        ``{ 0, 1, 1, 1 },``        ``{ 1, 0, 1, 0 },``        ``{ 1, 1, 0, 1 },``        ``{ 1, 0, 1, 0 },``    ``};` `    ``// Number of colors``    ``int` `m = 3;` `    ``// Function call``    ``graphColoring(graph, m);``    ``return` `0;``}` `// This code is contributed by Shivani`

## C

 `// C program for solution of M``// Coloring problem using backtracking` `#include ``#include ` `// Number of vertices in the graph``#define V 4` `void` `printSolution(``int` `color[]);` `/* A utility function to check if``   ``the current color assignment``   ``is safe for vertex v i.e. checks``   ``whether the edge exists or not``   ``(i.e, graph[v][i]==1). If exist``   ``then checks whether the color to``   ``be filled in the new vertex(c is``   ``sent in the parameter) is already``   ``used by its adjacent``   ``vertices(i-->adj vertices) or``   ``not (i.e, color[i]==c) */``bool` `isSafe(``int` `v, ``bool` `graph[V][V], ``int` `color[], ``int` `c)``{``    ``for` `(``int` `i = 0; i < V; i++)``        ``if` `(graph[v][i] && c == color[i])``            ``return` `false``;``    ``return` `true``;``}` `/* A recursive utility function``to solve m coloring problem */``bool` `graphColoringUtil(``bool` `graph[V][V], ``int` `m, ``int` `color[],``                       ``int` `v)``{``    ``/* base case: If all vertices are``       ``assigned a color then return true */``    ``if` `(v == V)``        ``return` `true``;` `    ``/* Consider this vertex v and``       ``try different colors */``    ``for` `(``int` `c = 1; c <= m; c++) {``        ``/* Check if assignment of color``           ``c to v is fine*/``        ``if` `(isSafe(v, graph, color, c)) {``            ``color[v] = c;` `            ``/* recur to assign colors to``               ``rest of the vertices */``            ``if` `(graphColoringUtil(graph, m, color, v + 1)``                ``== ``true``)``                ``return` `true``;` `            ``/* If assigning color c doesn't``               ``lead to a solution then remove it */``            ``color[v] = 0;``        ``}``    ``}` `    ``/* If no color can be assigned to``       ``this vertex then return false */``    ``return` `false``;``}` `/* This function solves the m Coloring``   ``problem using Backtracking. It mainly``   ``uses graphColoringUtil() to solve the``   ``problem. It returns false if the m``   ``colors cannot be assigned, otherwise``   ``return true and prints assignments of``   ``colors to all vertices. Please note``   ``that there may be more than one solutions,``   ``this function prints one of the``   ``feasible solutions.*/``bool` `graphColoring(``bool` `graph[V][V], ``int` `m)``{``    ``// Initialize all color values as 0.``    ``// This initialization is needed``    ``// correct functioning of isSafe()``    ``int` `color[V];``    ``for` `(``int` `i = 0; i < V; i++)``        ``color[i] = 0;` `    ``// Call graphColoringUtil() for vertex 0``    ``if` `(graphColoringUtil(graph, m, color, 0) == ``false``) {``        ``printf``(``"Solution does not exist"``);``        ``return` `false``;``    ``}` `    ``// Print the solution``    ``printSolution(color);``    ``return` `true``;``}` `/* A utility function to print solution */``void` `printSolution(``int` `color[])``{``    ``printf``(``"Solution Exists:"``           ``" Following are the assigned colors \n"``);``    ``for` `(``int` `i = 0; i < V; i++)``        ``printf``(``" %d "``, color[i]);``    ``printf``(``"\n"``);``}` `// Driver code``int` `main()``{``    ``/* Create following graph and test``       ``whether it is 3 colorable``      ``(3)---(2)``       ``|   / |``       ``|  /  |``       ``| /   |``      ``(0)---(1)``    ``*/``    ``bool` `graph[V][V] = {``        ``{ 0, 1, 1, 1 },``        ``{ 1, 0, 1, 0 },``        ``{ 1, 1, 0, 1 },``        ``{ 1, 0, 1, 0 },``    ``};``    ``int` `m = 3; ``// Number of colors` `    ``// Function call``    ``graphColoring(graph, m);``    ``return` `0;``}`

## Java

 `/* Java program for solution of``   ``M Coloring problem using backtracking */` `public` `class` `mColoringProblem {``    ``final` `int` `V = ``4``;``    ``int` `color[];` `    ``/* A utility function to check``       ``if the current color assignment``       ``is safe for vertex v */``    ``boolean` `isSafe(``int` `v, ``int` `graph[][], ``int` `color[], ``int` `c)``    ``{``        ``for` `(``int` `i = ``0``; i < V; i++)``            ``if` `(graph[v][i] == ``1` `&& c == color[i])``                ``return` `false``;``        ``return` `true``;``    ``}` `    ``/* A recursive utility function``       ``to solve m coloring  problem */``    ``boolean` `graphColoringUtil(``int` `graph[][], ``int` `m,``                              ``int` `color[], ``int` `v)``    ``{``        ``/* base case: If all vertices are``           ``assigned a color then return true */``        ``if` `(v == V)``            ``return` `true``;` `        ``/* Consider this vertex v and try``           ``different colors */``        ``for` `(``int` `c = ``1``; c <= m; c++) {``            ``/* Check if assignment of color c to v``               ``is fine*/``            ``if` `(isSafe(v, graph, color, c)) {``                ``color[v] = c;` `                ``/* recur to assign colors to rest``                   ``of the vertices */``                ``if` `(graphColoringUtil(graph, m, color,``                                      ``v + ``1``))``                    ``return` `true``;` `                ``/* If assigning color c doesn't lead``                   ``to a solution then remove it */``                ``color[v] = ``0``;``            ``}``        ``}` `        ``/* If no color can be assigned to``           ``this vertex then return false */``        ``return` `false``;``    ``}` `    ``/* This function solves the m Coloring problem using``       ``Backtracking. It mainly uses graphColoringUtil()``       ``to solve the problem. It returns false if the m``       ``colors cannot be assigned, otherwise return true``       ``and  prints assignments of colors to all vertices.``       ``Please note that there  may be more than one``       ``solutions, this function prints one of the``       ``feasible solutions.*/``    ``boolean` `graphColoring(``int` `graph[][], ``int` `m)``    ``{``        ``// Initialize all color values as 0. This``        ``// initialization is needed correct``        ``// functioning of isSafe()``        ``color = ``new` `int``[V];``        ``for` `(``int` `i = ``0``; i < V; i++)``            ``color[i] = ``0``;` `        ``// Call graphColoringUtil() for vertex 0``        ``if` `(!graphColoringUtil(graph, m, color, ``0``)) {``            ``System.out.println(``"Solution does not exist"``);``            ``return` `false``;``        ``}` `        ``// Print the solution``        ``printSolution(color);``        ``return` `true``;``    ``}` `    ``/* A utility function to print solution */``    ``void` `printSolution(``int` `color[])``    ``{``        ``System.out.println(``"Solution Exists: Following"``                           ``+ ``" are the assigned colors"``);``        ``for` `(``int` `i = ``0``; i < V; i++)``            ``System.out.print(``" "` `+ color[i] + ``" "``);``        ``System.out.println();``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String args[])``    ``{``        ``mColoringProblem Coloring = ``new` `mColoringProblem();``        ``/* Create following graph and``           ``test whether it is``           ``3 colorable``          ``(3)---(2)``           ``|   / |``           ``|  /  |``           ``| /   |``          ``(0)---(1)``        ``*/``        ``int` `graph[][] = {``            ``{ ``0``, ``1``, ``1``, ``1` `},``            ``{ ``1``, ``0``, ``1``, ``0` `},``            ``{ ``1``, ``1``, ``0``, ``1` `},``            ``{ ``1``, ``0``, ``1``, ``0` `},``        ``};``        ``int` `m = ``3``; ``// Number of colors` `        ``// Function call``        ``Coloring.graphColoring(graph, m);``    ``}``}``// This code is contributed by Abhishek Shankhadhar`

## Python3

 `# Python3 program for solution of M Coloring``# problem using backtracking`  `class` `Graph():` `    ``def` `__init__(``self``, vertices):``        ``self``.V ``=` `vertices``        ``self``.graph ``=` `[[``0` `for` `column ``in` `range``(vertices)]``                      ``for` `row ``in` `range``(vertices)]` `    ``# A utility function to check``    ``# if the current color assignment``    ``# is safe for vertex v``    ``def` `isSafe(``self``, v, colour, c):``        ``for` `i ``in` `range``(``self``.V):``            ``if` `self``.graph[v][i] ``=``=` `1` `and` `colour[i] ``=``=` `c:``                ``return` `False``        ``return` `True` `    ``# A recursive utility function to solve m``    ``# coloring  problem``    ``def` `graphColourUtil(``self``, m, colour, v):``        ``if` `v ``=``=` `self``.V:``            ``return` `True` `        ``for` `c ``in` `range``(``1``, m ``+` `1``):``            ``if` `self``.isSafe(v, colour, c) ``=``=` `True``:``                ``colour[v] ``=` `c``                ``if` `self``.graphColourUtil(m, colour, v ``+` `1``) ``=``=` `True``:``                    ``return` `True``                ``colour[v] ``=` `0` `    ``def` `graphColouring(``self``, m):``        ``colour ``=` `[``0``] ``*` `self``.V``        ``if` `self``.graphColourUtil(m, colour, ``0``) ``=``=` `None``:``            ``return` `False` `        ``# Print the solution``        ``print``(``"Solution exist and Following are the assigned colours:"``)``        ``for` `c ``in` `colour:``            ``print``(c, end``=``' '``)``        ``return` `True`  `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``g ``=` `Graph(``4``)``    ``g.graph ``=` `[[``0``, ``1``, ``1``, ``1``], [``1``, ``0``, ``1``, ``0``], [``1``, ``1``, ``0``, ``1``], [``1``, ``0``, ``1``, ``0``]]``    ``m ``=` `3` `    ``# Function call``    ``g.graphColouring(m)` `# This code is contributed by Divyanshu Mehta`

## C#

 `/* C# program for solution of M Coloring problem``using backtracking */``using` `System;` `class` `GFG {``    ``readonly` `int` `V = 4;``    ``int``[] color;` `    ``/* A utility function to check if the current``    ``color assignment is safe for vertex v */``    ``bool` `isSafe(``int` `v, ``int``[, ] graph, ``int``[] color, ``int` `c)``    ``{``        ``for` `(``int` `i = 0; i < V; i++)``            ``if` `(graph[v, i] == 1 && c == color[i])``                ``return` `false``;``        ``return` `true``;``    ``}` `    ``/* A recursive utility function to solve m``    ``coloring problem */``    ``bool` `graphColoringUtil(``int``[, ] graph, ``int` `m,``                           ``int``[] color, ``int` `v)``    ``{``        ``/* base case: If all vertices are assigned``        ``a color then return true */``        ``if` `(v == V)``            ``return` `true``;` `        ``/* Consider this vertex v and try different``        ``colors */``        ``for` `(``int` `c = 1; c <= m; c++) {``            ``/* Check if assignment of color c to v``            ``is fine*/``            ``if` `(isSafe(v, graph, color, c)) {``                ``color[v] = c;` `                ``/* recur to assign colors to rest``                ``of the vertices */``                ``if` `(graphColoringUtil(graph, m, color,``                                      ``v + 1))``                    ``return` `true``;` `                ``/* If assigning color c doesn't lead``                ``to a solution then remove it */``                ``color[v] = 0;``            ``}``        ``}` `        ``/* If no color can be assigned to this vertex``        ``then return false */``        ``return` `false``;``    ``}` `    ``/* This function solves the m Coloring problem using``    ``Backtracking. It mainly uses graphColoringUtil()``    ``to solve the problem. It returns false if the m``    ``colors cannot be assigned, otherwise return true``    ``and prints assignments of colors to all vertices.``    ``Please note that there may be more than one``    ``solutions, this function prints one of the``    ``feasible solutions.*/``    ``bool` `graphColoring(``int``[, ] graph, ``int` `m)``    ``{``        ``// Initialize all color values as 0. This``        ``// initialization is needed correct functioning``        ``// of isSafe()``        ``color = ``new` `int``[V];``        ``for` `(``int` `i = 0; i < V; i++)``            ``color[i] = 0;` `        ``// Call graphColoringUtil() for vertex 0``        ``if` `(!graphColoringUtil(graph, m, color, 0)) {``            ``Console.WriteLine(``"Solution does not exist"``);``            ``return` `false``;``        ``}` `        ``// Print the solution``        ``printSolution(color);``        ``return` `true``;``    ``}` `    ``/* A utility function to print solution */``    ``void` `printSolution(``int``[] color)``    ``{``        ``Console.WriteLine(``"Solution Exists: Following"``                          ``+ ``" are the assigned colors"``);``        ``for` `(``int` `i = 0; i < V; i++)``            ``Console.Write(``" "` `+ color[i] + ``" "``);``        ``Console.WriteLine();``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``GFG Coloring = ``new` `GFG();` `        ``/* Create following graph and test whether it is``        ``3 colorable``        ``(3)---(2)``        ``| / |``        ``| / |``        ``| / |``        ``(0)---(1)``        ``*/``        ``int``[, ] graph = { { 0, 1, 1, 1 },``                          ``{ 1, 0, 1, 0 },``                          ``{ 1, 1, 0, 1 },``                          ``{ 1, 0, 1, 0 } };``        ``int` `m = 3; ``// Number of colors` `        ``// Function call``        ``Coloring.graphColoring(graph, m);``    ``}``}` `// This code is contributed by PrinciRaj1992`

## Javascript

 ``

Output

```Solution Exists: Following are the assigned colors
1  2  3  2
```

Time Complexity: O(mV). There is a total of O(mV) combinations of colors. The upper bound time complexity remains the same but the average time taken will be less.
Auxiliary Space: O(V). The recursive Stack of the graph coloring function will require O(V) space.

Another Approach: Using BFS( Breadth- First-Search)

First, begin the BFS traversal.

Secondly, Discover the nearby (neighbouring) nodes to the present node. Give the neighbouring node the following colour if the current node’s colour and the adjacent node’s colour match. Verify whether or not the current node has been visited. If it hasn’t been visited yet, mark it as visited and put it in a queue.
Finally, Verify whether the colour is available. Return if the scenario changes to false.  Carry out the action on each of the nodes that have been supplied.(all the nodes)

## Java

 `// Java Code``import` `java.io.*;``import` `java.util.*;``class` `Node {``    ``int` `color = ``1``;``    ``Set edges = ``new` `HashSet();``}``public` `class` `mColoring {``    ``static` `int` `possiblePaint(ArrayList nodes, ``int` `n,``                             ``int` `m)``    ``{` `        ``// Create a visited array of n nodes``        ``ArrayList visited``            ``= ``new` `ArrayList();``        ``for` `(``int` `i = ``0``; i < n + ``1``; i++) {``            ``visited.add(``0``);``        ``}` `        ``// maxColors used till now are 1 as``        ``// all nodes are painted color 1``        ``int` `maxColors = ``1``;` `        ``for` `(``int` `sv = ``1``; sv <= n; sv++) {``            ``if` `(visited.get(sv) > ``0``) {``                ``continue``;``            ``}` `            ``// If the starting point is unvisited,``            ``// mark it visited and push it in queue``            ``visited.set(sv, ``1``);``            ``Queue q = ``new` `LinkedList<>();``            ``q.add(sv);` `            ``// BFS``            ``while` `(q.size() != ``0``) {``                ``int` `top = q.peek();``                ``q.remove();` `                ``// Checking all adjacent nodes``                ``// to "top" edge in our queue``                ``for` `(``int` `it : nodes.get(top).edges) {` `                    ``// If the color of the``                    ``// adjacent node is same, increase it by``                    ``// 1``                    ``if` `(nodes.get(top).color``                        ``== nodes.get(it).color) {``                        ``nodes.get(it).color += ``1``;``                    ``}` `                    ``// If number of colors used exceeds m,``                    ``// return 0``                    ``maxColors = Math.max(``                        ``maxColors,``                        ``Math.max(nodes.get(top).color,``                                 ``nodes.get(it).color));``                    ``if` `(maxColors > m)``                        ``return` `0``;` `                    ``// If the adjacent node is not visited,``                    ``// mark it visited and push it in queue``                    ``if` `(visited.get(it) == ``0``) {``                        ``visited.set(it, ``1``);``                        ``q.remove(it);``                    ``}``                ``}``            ``}``        ``}``        ``return` `1``;``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `n = ``4``;``        ``int``[][] graph = { { ``0``, ``1``, ``1``, ``1` `},``                          ``{ ``1``, ``0``, ``1``, ``0` `},``                          ``{ ``1``, ``1``, ``0``, ``1` `},``                          ``{ ``1``, ``0``, ``1``, ``0` `} };``        ``int` `m = ``3``; ``// Number of colors` `        ``ArrayList nodes = ``new` `ArrayList();` `        ``for` `(``int` `i = ``0``; i < n + ``1``; i++) {``            ``nodes.add(``new` `Node());``        ``}` `        ``// Add edges to each node as per given input``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``for` `(``int` `j = ``0``; j < n; j++) {``                ``if` `(graph[i][j] > ``0``) {``                    ``nodes.get(i).edges.add(i);``                    ``nodes.get(j).edges.add(j);``                ``}``            ``}``        ``}` `        ``int` `res = possiblePaint(nodes, n, m);``        ``if` `(res == ``1``) {``            ``System.out.println(``"True"``);``        ``}``        ``else` `{``            ``System.out.println(``"False"``);``        ``}``    ``}``}`

Output

```True
```

Time Complexity: O(V + E).
Auxiliary Space: O(V).

My Personal Notes arrow_drop_up