M-Coloring Problem | Practice | GeeksforGeeks

Given an undirected graph and an integer M. The task is to 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. Here coloring of a graph means the assignment of colors to all vertices. Print 1 if it is possible to colour vertices and 0 otherwise.
Example 1:
Input:
N = 4
M = 3
E = 5
Edges[] = {(0,1),(1,2),(2,3),(3,0),(0,2)}
Output: 1
Explanation: It is possible to colour the
given graph using 3 colours.

Example 2:
Input:
N = 3
M = 2
E = 3
Edges[] = {(0,1),(1,2),(0,2)}
Output: 0
Your Task:
Your task is to complete the function graphColoring() which takes the 2d-array graph[], the number of colours and the number of nodes as inputs and returns true if answer exists otherwise false. 1 is printed if the returned value is true, 0 otherwise. The printing is done by the driver's code.
Note: In Example there are Edges not the graph.Graph will be like, if there is an edge between vertex X and vertex Y graph[] will contain 1 at graph[X-1][Y-1], else 0. In 2d-array graph[ ], nodes are 0-based indexed, i.e. from 0 to N-1.Function will be contain 2-D graph not the edges.

Expected Time Complexity: O(MN).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ N ≤ 20
1 ≤ E ≤ (N*(N-1))/2
1 ≤ M ≤ N
0
ydahanh
This comment was deleted.
0
milindprajapatmst194 days ago
Total Time Taken: 0.04/1.06
Idea: dfs
 
const int N = 20;
int color[N];

bool check(int u, int n, int c, bool graph[101][101]) {
    for (int v = 0; v < n; v++) {
        if (u != v && graph[u][v] && color[v] == c)
            return true;
    }
    return false;
}

bool help(int u, int n, int m, bool graph[101][101]) {
    if (u == n)
        return true;
    for (int c = 0; c < m; c++) {
        if (check(u, n, c, graph))
            continue;
        color[u] = c;
        if (help(u + 1, n, m, graph))
            return true;
        color[u] = -1;
    }
    return false;
}

bool graphColoring(bool graph[101][101], int m, int n) {
    memset(color, -1, sizeof(color));
    return help(0, n, m, graph);
}
+1
akshu199bhardwaj2 weeks ago
Can anyone tell why all tcs are not passing with this code?
 
int colour[101]={0};bool isvalid(int c, int n,bool graph[101][101], int m, int v){   for(int j=0; j<v; j++)  {       if(j!=n && graph[j][n]==1 && colour[j]==c)       return false;  }   return true;}bool helper(int n, bool graph[101][101], int m, int v){   if(n==v)   return 1;   for(int i=1; i<=m; i++){      if(isvalid(i,n,graph,m,v))      {          colour[n]=i;          if(helper(n+1,graph,m,v))          return true;          colour[n]=0;      }               }return false;   }
bool graphColoring(bool graph[101][101], int m, int v){  if(helper(0,graph,m,v)) return true;  return 0;}
0
gaurav_1k32 weeks ago
//working code
bool isPossibleToColor(int node,int color[],bool graph[101][101],int V,int col){
   
   for(int i=0;i<V;i++){
       if(i!=node and graph[node][i]==1 and color[i]==col)
           return false;
   }
   return true;
}
bool solve(int node ,bool graph[101][101],int m, int V,int color[]){
   if(node==V) return true;
   
   for(int i=1;i<=m;i++){
       if(isPossibleToColor(node,color,graph,V,i)){
           color[node] = i;
           if(solve(node+1,graph,m,V,color)) return true;
           color[node] = 0;
       }
   }
   return false;
}

bool graphColoring(bool graph[101][101], int m, int V)
{
   // your code here
   int color[V] = {0};
   if(solve(0,graph,m,V,color)==true) return true;
   return false;
}
0
khanarshad26002 weeks ago
Easy Java Solution _________
public static boolean graphColoring(List<Integer>[] G, int[] color, int i, int m){       if(i == G.length) return true;              for(int c=1; c<=m; c++){           if(isSafe(G, color, i, c)){               color[i] = c;               if(graphColoring(G, color, i+1, m)) return true;               color[i] = 0;           }       }              return false;   }      public static boolean isSafe(List<Integer>[] G, int[] color, int i, int c){       for(int adj : G[i]){           if(color[adj] == c) return false;       }       return true;   }
0
sunboykenneth2 weeks ago
bool graphColoringImpl (bool graph[101][101], int M, int V, int curVertice, vector<int>& verticeColors)
{
    if (curVertice == V) {
        return true;
    }
    
    vector<bool> colorAvailable = vector<bool>(M, true);
    for (int i = 0; i < curVertice; i++) {
        if (graph[curVertice][i] == 0) {
            continue;
        }
        
        colorAvailable[verticeColors[i]] = false;
    }
    
    // Use available colors for current vertice
    for (int i = 0 ; i < M; i++) {
        if (colorAvailable[i] == false) {
            continue;
        }
        
        verticeColors[curVertice] = i;
        if( graphColoringImpl(graph, M, V, curVertice + 1, verticeColors) == true) {
            return true;
        }
        verticeColors[curVertice] = -1;
    }
    
    return false;
}


bool graphColoring(bool graph[101][101], int M, int V)
{
    if (M == 0) {
        return V == 0;
    }
    
    if (V <= M) {
        return true;
    }
    
    vector<int> verticeColors = vector<int>(V, -1);
    return graphColoringImpl(graph, M, V, 0, verticeColors);
}
-1
amateur_973 weeks ago
How is the site still popular beats me.
For the Java problem, atleast tell what the parameters are?!
0
devashishbakare3 weeks ago
JAVA Solution with comments
 
public static boolean graphColoring(List<Integer>[] G, int[] color, int i, int m) 
    {
       return solve(G, color, i, m);
    }
    
    
    public static boolean solve(List<Integer>[] graph, int color[], int ind, int total_clr)
    {
        //base case
        if(ind == graph.length)
        return true;
        
        //explore all the color
        for(int i = 1 ; i <= total_clr ; i++ )
        {
            //check whether a color is assign to adjacent or not
            if(check(ind, graph, color, i))
            {
                //its safe to add this color so we need to add this color
                color[ind] = i;
                //call to its adjacent to check next color on there index
                if(solve(graph, color, ind+1, total_clr) == true) return true;
                //if not possible this color remove that color
                color[ind] = 0;
            }
        }
        
        //by exploring all the option we still not return result then return false;
        return false;
    }
    
    public static boolean check(int ind, List<Integer> []graph, int color[], int col)
    {
        //we have a color then we have to check the adjacent have same color or not
        for(int i :graph[ind])
        {
            if(color[i] == col)
            //if yes return false saying this color your pass not possible
            return false;
        }
        //if adjacent  not have the same color then return a true
        return true;
    }
0
avinashdhn19043 weeks ago
// C++ solution

bool isSafe(int node,bool graph[101][101],int color[],int n,int col){
    
    for(int i=0;i<n;i++){
        if((i!=node)&&graph[node][i]&&color[i]==col)return false;
    }
    return true;
}
bool solve(int node,bool graph[101][101],int color[],int n,int m){
    if(node==n)return true;
    for(int i=1;i<=m;i++){
        if(isSafe(node,graph,color,n,i)){
            color[node]=i;
            if(solve(node+1,graph,color,n,m))return true;
            color[node]=0;
        }
    }
    return false;
    
}
bool graphColoring(bool graph[101][101], int m, int V)
{
    int n=V;
    int color[n];
    memset(color,0,sizeof(color));
      return solve(0,graph,color,n,m);
}
0
asissrmakumar6661 month ago
JAVA | BackTracking 
class solve {
    public static boolean graphColoring(List<Integer>[] G, int[] color, int i, int m) {
        return check(i,G.length,G,color,m);
    }
    public static boolean check(int node,int n,List<Integer> []G,int []color,int m){
        if(node==n) return true;
        for(int i=1;i<=m;i++){
            if(isPossible(i,G,node,color)){
                color[node]=i;
                if(check(node+1,n,G,color,m)) return true;
                color[node]=0;
            }
        }
        return false;
    } 
    public static boolean isPossible(int clr,List<Integer> []G,int node,int []color){
        for(int k:G[node]){
            if(color[k]==clr) return false;
        }
        return true;
    }
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.