m Coloring Problem using c or c++
m Coloring Problem using c or c++
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. Here coloring of a graph means the assignment of colors to all vertices.
Input:
1) A 2D array graph[V][V] where V is the number of vertices in graph and graph[V][V] is adjacency matrix representation of the graph. A value graph[i][j] is 1 if there is a direct edge from i to j, otherwise graph[i][j] is 0.
2) An integer m which is a maximum number of colors that can be used.
1) A 2D array graph[V][V] where V is the number of vertices in graph and graph[V][V] is adjacency matrix representation of the graph. A value graph[i][j] is 1 if there is a direct edge from i to j, otherwise graph[i][j] is 0.
2) An integer m which is a maximum number of colors that can be used.
Output:
An array color[V] that should have numbers from 1 to m. color[i] should represent the color assigned to the ith vertex. The code should also return false if the graph cannot be colored with m colors.
Program:
An array color[V] that should have numbers from 1 to m. color[i] should represent the color assigned to the ith vertex. The code should also return false if the graph cannot be colored with m colors.
Program:
#include <conio.h>
#include <math.h>
int m,n,x[10]={0},g[10][10]={0};
void main()
{
int i,j; void mcolor();
printf("No. of colors available: ");
scanf("%d",&m);
printf("No. of regions: ") ;
scanf("%d",&n) ;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
printf("g[%d][%d] = ",i,j) ;
scanf("%d",&g[i][j]) ;
}
mcolor();
getch();
}
void mcolor()
{
int i,k=1,backtrack(int),solution(int) ;
void printsol() ;
while(k!=0)
{
x[k]=(x[k]+1)%(m+1) ;
printf("x[%d] = %d\n",k,x[k]) ; getch() ;
if(x[k]!=0)
{
if(backtrack(k))
continue ;
if(solution(k))
{
printsol() ;
return ;
}
else
k++ ;
}
else
{
printf("%d colors are not sufficient\n",m) ;
return ;
}
}
}
int backtrack(int k)
{
int j;
for(j=1;j<k;j++)
if(g[j][k]==1 && x[j]==x[k])
{
return 1;
}
return 0;
}
int solution(int k)
{
if(k==n)
return 1 ;
else
return 0 ;
}
void printsol()
{
printf("Solution is : ") ;
for(int j=1;j<=n;j++)
printf("%d ",x[j]);
printf("\n");
}
stindia0dispri-Madison Andrew Straka Crack
ReplyDeletearweipuphand