Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

22103091

Week-4
Problem 7: Program to solve Graph Coloring problem.
Description:
In this problem, an undirected graph is given. There is also provided m colors. The problem is
to find if it is possible to assign nodes with m different colors, such that no two adjacent
vertices of the graph are of the same colors. If the solution exists, then display which color is
assigned on which vertex.
ALGORITHM:
isValid(vertex, colorList, col):

Begin
for all vertices v of the graph, do
if there is an edge between v and i, and col = colorList[i], then
return false
done
return true
End
graphColoring(colors, colorList, vertex):
Begin
if all vertices are checked, then
return true
for all colors col from available colors, do
if isValid(vertex, color, col), then
add col to the colorList for vertex
if graphColoring(colors, colorList, vertex+1) = true, then
return true
remove color for vertex
done
return false
End

Time Complexity:

Time Complexity: O(M^V). Reason: Choosing out of M given colors for V vertices will lead
to an O(M^V) combination. So the time complexity is O(M^V).

32
22103091

SOURCE CODE:
#include<bits/stdc++.h>
using namespace std;

bool isSafe(vector<vector<int>>&graph,vector<int> &color,int v,int c){


for(int i=0;i<graph.size();i++){
if(graph[i][v] & c == color[i]){
return false;
}
}
return true;
}

bool colorg(vector<vector<int>>&graph,int m, vector<int> &color,int s){


if(s==graph.size())
return true;
for(int i=1;i<=m;i++){
if(isSafe(graph,color,s,i)==true){
color[s]=i;
if(colorg(graph,m,color,s+1)==true)
return true;
color[s]=0;
}
}
return false;
}
int main(){
vector<vector<int>> graph={
{0,1,1,1,0},
{1,0,1,0,1},
{1,1,0,1,0},
{1,0,1,0,0},
{0,1,0,0,0}
};
int n=graph.size();
int m=3;
vector<int>color(n,0);
if(colorg(graph,m,color,0)==false){
cout<<"Coloring is Not possible";
return 0;
}
else{
cout<<"Color of Vertices are: "<<endl;
for(int i=0;i<n;i++){
cout<<color[i]<<" ";
}
}
return 0;}

33
22103091

OUTPUT:

34

You might also like