Given an undirected graph consisting of V vertices represented by an adjacency list adj[][] and an integer m, check whether the graph can be colored using at most m different colors such that no two adjacent vertices have the same color.
Note: The graph uses 0-based indexing and may be connected or disconnected.
Examples
Input: adj[][] = [[1, 3, 2], [0, 3], [3, 0], [1, 2, 0]], m = 3 Output: true Explanation: Structure allows enough separation between connected vertices, so using 3 colors is sufficient to ensure no two adjacent vertices share the same color—hence, the answer is true
Input: adj[][] = [[1, 2], [0, 2], [0, 1]], m = 2 Output: false Explanation: It is not possible to color the given graph using only 2 colors because vertices 0, 1, and 2 form a triangle.
Generate All Colorings - O((V + E)*m^V) Time and O(V + E) Space
Generate all possible colorings of the V vertices. Since each vertex can have any of the m colors, there are (m^V) possible colorings.
For each coloring, check whether any two adjacent vertices have the same color.
If a valid coloring is found, return true.
If no valid coloring exists after checking all possibilities, return false.
C++
#include<bits/stdc++.h>usingnamespacestd;// Function to check whether the current coloring is validboolgoodcolor(vector<vector<int>>&adj,vector<int>col){for(inti=0;i<col.size();i++){for(autoit:adj[i]){// Check if adjacent vertices have the same colorif(i!=it&&col[i]==col[it])returnfalse;}}returntrue;}// Recursive function to generate all possible coloringsboolgenerateColor(inti,vector<int>col,intm,vector<vector<int>>&adj){// If all vertices are colored, check whether the coloring is validif(i>=col.size()){if(goodcolor(adj,col))returntrue;returnfalse;}// Try all colors from 0 to m-1for(intj=0;j<m;j++){col[i]=j;if(generateColor(i+1,col,m,adj))returntrue;// Backtrack by resetting the current vertex colorcol[i]=-1;}returnfalse;}// Function to check if the graph can be colored with m colorsboolgraphColoring(vector<vector<int>>&adj,intm){intv=adj.size();// Initialize all vertices with no colorvector<int>color(v,-1);returngenerateColor(0,color,m,adj);}intmain(){vector<vector<int>>adj={{1,2,3},{0,3},{0,3},{0,1,2}};intm=3;// Check if the graph can be colored with m colors// such that no adjacent vertices share the same colorcout<<(graphColoring(adj,m)?"true":"false")<<endl;return0;}
Java
importjava.util.ArrayList;importjava.util.Arrays;importjava.util.Collections;classGFG{// Function to check whether the current coloring is validstaticbooleangoodcolor(ArrayList<ArrayList<Integer>>adj,ArrayList<Integer>col){for(inti=0;i<col.size();i++){for(intit:adj.get(i)){// Check if adjacent vertices have the same colorif(i!=it&&col.get(i).equals(col.get(it)))returnfalse;}}returntrue;}// Recursive function to generate all possible coloringsstaticbooleangenerateColor(inti,ArrayList<Integer>col,intm,ArrayList<ArrayList<Integer>>adj){// If all vertices are colored, check whether the coloring is validif(i>=col.size()){if(goodcolor(adj,col))returntrue;returnfalse;}// Try all colors from 0 to m-1for(intj=0;j<m;j++){col.set(i,j);if(generateColor(i+1,newArrayList<>(col),m,adj))returntrue;// Backtrack by resetting the current vertex colorcol.set(i,-1);}returnfalse;}// Function to check if the graph can be colored with m colorsstaticbooleangraphColoring(ArrayList<ArrayList<Integer>>adj,intm){intv=adj.size();// Initialize all vertices with no colorArrayList<Integer>color=newArrayList<>(Collections.nCopies(v,-1));returngenerateColor(0,color,m,adj);}publicstaticvoidmain(String[]args){ArrayList<ArrayList<Integer>>adj=newArrayList<>();adj.add(newArrayList<>(Arrays.asList(1,2,3)));adj.add(newArrayList<>(Arrays.asList(0,3)));adj.add(newArrayList<>(Arrays.asList(0,3)));adj.add(newArrayList<>(Arrays.asList(0,1,2)));intm=3;System.out.println(graphColoring(adj,m)?"true":"false");}}
Python
# Function to check whether the current coloring is validdefgoodcolor(adj,col):foriinrange(len(col)):foritinadj[i]:# Check if adjacent vertices have the same colorifi!=itandcol[i]==col[it]:returnFalsereturnTrue# Recursive function to generate all possible coloringsdefgenerateColor(i,col,m,adj):# If all vertices are colored, check whether the coloring is validifi>=len(col):ifgoodcolor(adj,col):returnTruereturnFalse# Try all colors from 0 to m-1forjinrange(m):col[i]=jifgenerateColor(i+1,col.copy(),m,adj):returnTrue# Backtrack by resetting the current vertex colorcol[i]=-1returnFalse# Function to check if the graph can be colored with m colorsdefgraphColoring(adj,m):v=len(adj)# Initialize all vertices with no colorcolor=[-1]*vreturngenerateColor(0,color,m,adj)if__name__=="__main__":adj=[[1,2,3],[0,3],[0,3],[0,1,2]]m=3print("true"ifgraphColoring(adj,m)else"false")
C#
usingSystem;usingSystem.Collections.Generic;classGFG{// Function to check whether the current coloring is validstaticboolgoodcolor(List<List<int>>adj,List<int>col){for(inti=0;i<col.Count;i++){foreach(intitinadj[i]){// Check if adjacent vertices have the same colorif(i!=it&&col[i]==col[it])returnfalse;}}returntrue;}// Recursive function to generate all possible coloringsstaticboolgenerateColor(inti,List<int>col,intm,List<List<int>>adj){// If all vertices are colored, check whether the coloring is validif(i>=col.Count){if(goodcolor(adj,col))returntrue;returnfalse;}// Try all colors from 0 to m-1for(intj=0;j<m;j++){col[i]=j;if(generateColor(i+1,newList<int>(col),m,adj))returntrue;// Backtrack by resetting the current vertex colorcol[i]=-1;}returnfalse;}// Function to check if the graph can be colored with m colorsstaticboolgraphColoring(List<List<int>>adj,intm){intv=adj.Count;// Initialize all vertices with no colorList<int>color=newList<int>();for(inti=0;i<v;i++)color.Add(-1);returngenerateColor(0,color,m,adj);}staticvoidMain(){List<List<int>>adj=newList<List<int>>{newList<int>{1,2,3},newList<int>{0,3},newList<int>{0,3},newList<int>{0,1,2}};intm=3;Console.WriteLine(graphColoring(adj,m)?"true":"false");}}
JavaScript
// Function to check whether the current coloring is validfunctiongoodcolor(adj,col){for(leti=0;i<col.length;i++){for(letitofadj[i]){// Check if adjacent vertices have the same colorif(i!==it&&col[i]===col[it])returnfalse;}}returntrue;}// Recursive function to generate all possible coloringsfunctiongenerateColor(i,col,m,adj){// If all vertices are colored, check whether the coloring is validif(i>=col.length){if(goodcolor(adj,col))returntrue;returnfalse;}// Try all colors from 0 to m-1for(letj=0;j<m;j++){col[i]=j;if(generateColor(i+1,[...col],m,adj))returntrue;// Backtrack by resetting the current vertex colorcol[i]=-1;}returnfalse;}// Function to check if the graph can be colored with m colorsfunctiongraphColoring(adj,m){letv=adj.length;// Initialize all vertices with no colorletcolor=newArray(v).fill(-1);returngenerateColor(0,color,m,adj);}// Driver codeletadj=[[1,2,3],[0,3],[0,3],[0,1,2]];letm=3;console.log(graphColoring(adj,m)?"true":"false");
Output
true
Backtracking - O(V * m^V) Time and O(V + E) Space
Assign colors to vertices one by one, starting from vertex 0. Before assigning a color, check whether any adjacent vertex already has the same color.
Try all available colors from 0 to m-1 for the current vertex.
If a color is valid, assign it and recursively color the next vertex.
If no valid color is available, backtrack by resetting the current vertex's color and try another possibility.
If all vertices are colored successfully, return true; otherwise, return false.
Illustration:
C++
#include<bits/stdc++.h>usingnamespacestd;// Function to check if it's safe to color the current vertex// with the given colorboolissafe(intvertex,intcol,vector<vector<int>>&adj,vector<int>&color){for(autoit:adj[vertex]){// If adjacent vertex has the same color, not safeif(color[it]!=-1&&col==color[it])returnfalse;}returntrue;}// Recursive function to try all coloringsboolcancolor(intvertex,intm,vector<vector<int>>&adj,vector<int>&color){// If all vertices are colored successfullyif(vertex==color.size())returntrue;// Try all colors from 0 to m-1for(inti=0;i<m;i++){if(issafe(vertex,i,adj,color)){color[vertex]=i;if(cancolor(vertex+1,m,adj,color))// If the rest can be colored, return truereturntrue;color[vertex]=-1;}}// No valid coloring foundreturnfalse;}boolgraphColoring(vector<vector<int>>&adj,intm){intv=adj.size();vector<int>color(v,-1);returncancolor(0,m,adj,color);}intmain(){vector<vector<int>>adj={{1,2,3},{0,3},{0,3},{0,1,2}};intm=3;// Check if the graph can be colored with m colors// such that no adjacent vertices share the same colorcout<<(graphColoring(adj,m)?"true":"false")<<endl;return0;}
Java
importjava.util.ArrayList;importjava.util.Collections;importjava.util.Arrays;classGFG{// Function to check if it's safe to color the current vertex// with the given colorstaticbooleanissafe(intvertex,intcol,ArrayList<ArrayList<Integer>>adj,ArrayList<Integer>color){for(intit:adj.get(vertex)){// If adjacent vertex has the same color, not safeif(color.get(it)!=-1&&col==color.get(it))returnfalse;}returntrue;}// Recursive function to try all coloringsstaticbooleancancolor(intvertex,intm,ArrayList<ArrayList<Integer>>adj,ArrayList<Integer>color){// If all vertices are colored successfullyif(vertex==color.size())returntrue;// Try all colors from 0 to m-1for(inti=0;i<m;i++){if(issafe(vertex,i,adj,color)){color.set(vertex,i);if(cancolor(vertex+1,m,adj,color))// If the rest can be colored, return truereturntrue;color.set(vertex,-1);}}// No valid coloring foundreturnfalse;}staticbooleangraphColoring(ArrayList<ArrayList<Integer>>adj,intm){intv=adj.size();ArrayList<Integer>color=newArrayList<>(Collections.nCopies(v,-1));returncancolor(0,m,adj,color);}publicstaticvoidmain(String[]args){ArrayList<ArrayList<Integer>>adj=newArrayList<>();adj.add(newArrayList<>(Arrays.asList(1,2,3)));adj.add(newArrayList<>(Arrays.asList(0,3)));adj.add(newArrayList<>(Arrays.asList(0,3)));adj.add(newArrayList<>(Arrays.asList(0,1,2)));intm=3;System.out.println(graphColoring(adj,m)?"true":"false");}}
Python
# Function to check if it's safe to color the current vertex# with the given colordefissafe(vertex,col,adj,color):foritinadj[vertex]:# If adjacent vertex has the same color, not safeifcolor[it]!=-1andcol==color[it]:returnFalsereturnTrue# Recursive function to try all coloringsdefcancolor(vertex,m,adj,color):# If all vertices are colored successfullyifvertex==len(color):returnTrue# Try all colors from 0 to m-1foriinrange(m):ifissafe(vertex,i,adj,color):color[vertex]=iifcancolor(vertex+1,m,adj,color):# If the rest can be colored, return truereturnTruecolor[vertex]=-1# No valid coloring foundreturnFalsedefgraphColoring(adj,m):v=len(adj)color=[-1]*vreturncancolor(0,m,adj,color)if__name__=="__main__":adj=[[1,2,3],[0,3],[0,3],[0,1,2]]m=3print("true"ifgraphColoring(adj,m)else"false")
C#
usingSystem;usingSystem.Collections.Generic;classGFG{// Function to check if it's safe to color the current vertex// with the given colorstaticboolissafe(intvertex,intcol,List<List<int>>adj,List<int>color){foreach(intitinadj[vertex]){// If adjacent vertex has the same color, not safeif(color[it]!=-1&&col==color[it])returnfalse;}returntrue;}// Recursive function to try all coloringsstaticboolcancolor(intvertex,intm,List<List<int>>adj,List<int>color){// If all vertices are colored successfullyif(vertex==color.Count)returntrue;// Try all colors from 0 to m-1for(inti=0;i<m;i++){if(issafe(vertex,i,adj,color)){color[vertex]=i;if(cancolor(vertex+1,m,adj,color))// If the rest can be colored, return truereturntrue;color[vertex]=-1;}}// No valid coloring foundreturnfalse;}staticboolgraphColoring(List<List<int>>adj,intm){intv=adj.Count;List<int>color=newList<int>();// Initialize all vertices with no colorfor(inti=0;i<v;i++)color.Add(-1);returncancolor(0,m,adj,color);}staticvoidMain(){List<List<int>>adj=newList<List<int>>{newList<int>{1,2,3},newList<int>{0,3},newList<int>{0,3},newList<int>{0,1,2}};intm=3;// Check if the graph can be colored with m colors// such that no adjacent vertices share the same colorConsole.WriteLine(graphColoring(adj,m)?"true":"false");}}
JavaScript
// Function to check if it's safe to color the current vertex// with the given colorfunctionissafe(vertex,col,adj,color){for(letitofadj[vertex]){// If adjacent vertex has the same color, not safeif(color[it]!==-1&&col===color[it])returnfalse;}returntrue;}// Recursive function to try all coloringsfunctioncancolor(vertex,m,adj,color){// If all vertices are colored successfullyif(vertex===color.length)returntrue;// Try all colors from 0 to m-1for(leti=0;i<m;i++){if(issafe(vertex,i,adj,color)){color[vertex]=i;if(cancolor(vertex+1,m,adj,color))// If the rest can be colored, return truereturntrue;color[vertex]=-1;}}// No valid coloring foundreturnfalse;}functiongraphColoring(adj,m){letv=adj.length;letcolor=newArray(v).fill(-1);returncancolor(0,m,adj,color);}// Driver codeletadj=[[1,2,3],[0,3],[0,3],[0,1,2]];letm=3;console.log(graphColoring(adj,m)?"true":"false");
Output
true
Time Complexity: O(V * m^V). There is a total of O(m^V) combinations of colors. For each attempted coloring of a vertex you call issafe(), can have up to V-1 neighbors, so issafe() is O(V) Auxiliary Space: O(V + E). The recursive Stack of the graph coloring function will require O(V) space, Adjacency list and color array will required O(V+E).