Given an edges of graph and a number m, the your task is to check it is possible to color the given graph with at most m colors such that no two adjacent vertices of the graph are colored with the same color.
Examples
Input: V = 4, edges[][] = [[0, 1], [0, 2], [0,3], [1, 3], [2, 3]], 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: V = 5, edges[][] = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 4], [2, 3], [2, 4], [3, 4]], m = 3 Output: false Explanation: In this graph, the vertices are highly interconnected, especially vertex 2, which connects to four others. With only 3 colors, it's impossible to assign colors so that no two adjacent vertices share the same color, hence, the answer is false.
Approach 1: Generate all possible configurations - O((V + E)*m^V) Time and O(E+V) Space
Generate all possible configurations of length V 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.
C++
#include<bits/stdc++.h>usingnamespacestd;boolgoodcolor(vector<int>adj[],vector<int>col){for(inti=0;i<col.size();i++){for(autoit:adj[i]){if(i!=it&&col[i]==col[it])returnfalse;}}returntrue;}boolgenratecolor(inti,vector<int>col,intm,vector<int>adj[]){if(i>=col.size()){if(goodcolor(adj,col))returntrue;returnfalse;}for(intj=0;j<m;j++){col[i]=j;if(genratecolor(i+1,col,m,adj))returntrue;col[i]=-1;}returnfalse;}boolgraphColoring(intv,vector<vector<int>>&edges,intm){vector<int>adj[v];// Build adjacency list from edgesfor(autoit:edges){adj[it[0]].push_back(it[1]);adj[it[1]].push_back(it[0]);}vector<int>color(v,-1);returngenratecolor(0,color,m,adj);}intmain(){intV=4;vector<vector<int>>edges={{0,1},{0,2},{0,3},{1,3},{2,3}};intm=3;// Check if the graph can be colored with m colors // such that no adjacent nodes share the same colorcout<<(graphColoring(V,edges,m)?"true":"false")<<endl;return0;}
Java
importjava.util.*;classGfG{staticbooleangoodcolor(List<Integer>adj[],int[]col){for(inti=0;i<col.length;i++){for(intit:adj[i]){if(i!=it&&col[i]==col[it])returnfalse;}}returntrue;}staticbooleangenratecolor(inti,int[]col,intm,List<Integer>adj[]){if(i>=col.length){if(goodcolor(adj,col))returntrue;returnfalse;}for(intj=0;j<m;j++){col[i]=j;if(genratecolor(i+1,col,m,adj))returntrue;col[i]=-1;}returnfalse;}staticbooleangraphColoring(intv,int[][]edges,intm){List<Integer>[]adj=newArrayList[v];// Build adjacency list from edgesfor(inti=0;i<v;i++){adj[i]=newArrayList<>();}for(int[]it:edges){adj[it[0]].add(it[1]);adj[it[1]].add(it[0]);}int[]color=newint[v];Arrays.fill(color,-1);returngenratecolor(0,color,m,adj);}publicstaticvoidmain(String[]args){intV=4;int[][]edges={{0,1},{0,2},{0,3},{1,3},{2,3}};intm=3;// Check if the graph can be colored with m colors// such that no adjacent nodes share the same colorSystem.out.println(graphColoring(V,edges,m)?"true":"false");}}
Python
defgoodcolor(adj,col):# Check if the coloring is validforiinrange(len(col)):foritinadj[i]:ifi!=itandcol[i]==col[it]:returnFalsereturnTruedefgenratecolor(i,col,m,adj):ifi>=len(col):ifgoodcolor(adj,col):returnTruereturnFalseforjinrange(m):col[i]=jifgenratecolor(i+1,col,m,adj):returnTruecol[i]=-1returnFalsedefgraphColoring(v,edges,m):adj=[[]for_inrange(v)]# Build adjacency list from edgesforu,winedges:adj[u].append(w)adj[w].append(u)color=[-1]*vreturngenratecolor(0,color,m,adj)# TestV=4edges=[[0,1],[0,2],[0,3],[1,3],[2,3]]m=3# Check if the graph can be colored with m colors# such that no adjacent nodes share the same colorprint("true"ifgraphColoring(V,edges,m)else"false")
C#
usingSystem;usingSystem.Collections.Generic;classGfG{staticboolgoodcolor(List<int>[]adj,int[]col){for(inti=0;i<col.Length;i++){foreach(intitinadj[i]){if(i!=it&&col[i]==col[it])returnfalse;}}returntrue;}staticboolgenratecolor(inti,int[]col,intm,List<int>[]adj){if(i>=col.Length){if(goodcolor(adj,col))returntrue;returnfalse;}for(intj=0;j<m;j++){col[i]=j;if(genratecolor(i+1,col,m,adj))returntrue;col[i]=-1;}returnfalse;}staticboolgraphColoring(intv,int[,]edges,intm){List<int>[]adj=newList<int>[v];// Build adjacency list from edgesfor(inti=0;i<v;i++){adj[i]=newList<int>();}for(inti=0;i<edges.GetLength(0);i++){intu=edges[i,0];intv2=edges[i,1];adj[u].Add(v2);adj[v2].Add(u);}int[]color=newint[v];for(inti=0;i<v;i++)color[i]=-1;returngenratecolor(0,color,m,adj);}publicstaticvoidMain(string[]args){intV=4;int[,]edges={{0,1},{0,2},{0,3},{1,3},{2,3}};intm=3;// Check if the graph can be colored with m colors// such that no adjacent nodes share the same colorConsole.WriteLine(graphColoring(V,edges,m)?"true":"false");}}
JavaScript
functiongoodcolor(adj,col){// Check if the coloring is validfor(leti=0;i<col.length;i++){for(letitofadj[i]){if(i!==it&&col[i]===col[it])returnfalse;}}returntrue;}functiongenratecolor(i,col,m,adj){if(i>=col.length){if(goodcolor(adj,col))returntrue;returnfalse;}for(letj=0;j<m;j++){col[i]=j;if(genratecolor(i+1,col,m,adj))returntrue;col[i]=-1;}returnfalse;}functiongraphColoring(v,edges,m){letadj=Array.from({length:v},()=>[]);// Build adjacency list from edgesfor(let[u,w]ofedges){adj[u].push(w);adj[w].push(u);}letcolor=newArray(v).fill(-1);returngenratecolor(0,color,m,adj);}// TestletV=4;letedges=[[0,1],[0,2],[0,3],[1,3],[2,3]];letm=3;// Check if the graph can be colored with m colors// such that no adjacent nodes share the same colorconsole.log(graphColoring(V,edges,m)?"true":"false");
Output
true
Approach 2: Using Backtracking - O(V * m^V) Time and O(V+E) Space
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
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<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<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(intv,vector<vector<int>>&edges,intm){vector<int>adj[v];// Build adjacency list from edgesfor(autoit:edges){adj[it[0]].push_back(it[1]);adj[it[1]].push_back(it[0]);}vector<int>color(v,-1);returncancolor(0,m,adj,color);}intmain(){intV=4;vector<vector<int>>edges={{0,1},{0,2},{0,3},{1,3},{2,3}};intm=3;// Check if the graph can be colored with m colors // such that no adjacent nodes share the same colorcout<<(graphColoring(V,edges,m)?"true":"false")<<endl;return0;}
Java
importjava.util.*;publicclassMain{// Function to check if it's safe to color the current // vertex with the given colorstaticbooleanissafe(intvertex,intcol,List<Integer>[]adj,int[]color){for(intit:adj[vertex]){// If adjacent vertex has the same color, not safeif(color[it]!=-1&&col==color[it])returnfalse;}returntrue;}// Recursive function to try all coloringsstaticbooleancancolor(intvertex,intm,List<Integer>[]adj,int[]color){// If all vertices are colored successfullyif(vertex==color.length)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;}}returnfalse;// No valid coloring found}staticbooleangraphColoring(intv,int[][]edges,intm){List<Integer>[]adj=newArrayList[v];for(inti=0;i<v;i++)adj[i]=newArrayList<>();// Build adjacency list from edgesfor(int[]it:edges){adj[it[0]].add(it[1]);adj[it[1]].add(it[0]);}int[]color=newint[v];Arrays.fill(color,-1);returncancolor(0,m,adj,color);}publicstaticvoidmain(String[]args){intV=4;int[][]edges={{0,1},{0,2},{0,3},{1,3},{2,3}};intm=3;// Check if the graph can be colored with m colors // such that no adjacent nodes share the same colorSystem.out.println(graphColoring(V,edges,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# Backtrack# No valid coloring foundreturnFalse# Main function to set up the graph and call coloring logicdefgraphColoring(v,edges,m):adj=[[]for_inrange(v)]# Build adjacency list from edgesforu,winedges:adj[u].append(w)adj[w].append(u)color=[-1]*vreturncancolor(0,m,adj,color)# Driver codeif__name__=="__main__":V=4edges=[[0,1],[0,2],[0,3],[1,3],[2,3]]m=3# Check if the graph can be colored with m colors# such that no adjacent nodes share the same colorprint("true"ifgraphColoring(V,edges,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<int>[]adj,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<int>[]adj,int[]color){// If all vertices are colored successfullyif(vertex==color.Length)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;}}returnfalse;// No valid coloring found}staticboolgraphColoring(intv,int[,]edges,intm){List<int>[]adj=newList<int>[v];for(inti=0;i<v;i++)adj[i]=newList<int>();// Build adjacency list from edgesfor(inti=0;i<edges.GetLength(0);i++){intu=edges[i,0];intv2=edges[i,1];adj[u].Add(v2);adj[v2].Add(u);}int[]color=newint[v];for(inti=0;i<v;i++)color[i]=-1;returncancolor(0,m,adj,color);}staticvoidMain(string[]args){intV=4;int[,]edges={{0,1},{0,2},{0,3},{1,3},{2,3}};intm=3;// Check if the graph can be colored with m colors // such that no adjacent nodes share the same colorConsole.WriteLine(graphColoring(V,edges,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;}// Main function to set up the graph and call coloring logicfunctiongraphColoring(v,edges,m){letadj=newArray(v).fill(0).map(()=>[]);// Build adjacency list from edgesfor(let[u,w]ofedges){adj[u].push(w);adj[w].push(u);}letcolor=newArray(v).fill(-1);returncancolor(0,m,adj,color);}// Driver codeconstV=4;constedges=[[0,1],[0,2],[0,3],[1,3],[2,3]];constm=3;// Check if the graph can be colored with m colors// such that no adjacent nodes share the same colorconsole.log(graphColoring(V,edges,m)?"true":"false");
Output
true
Time Complexity: O(V * mV). There is a total of O(mV) 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).