GRAPH COLOURING:
Given a graph G (V,E) where V represents the vertices in the graph and E represents the edges in the graph . Given m different colours to colour the nodes in such a way that no two adjacent nodes are of same colour.
eg:
for the given graph
and given two colours yellow and red
there are two solutions possible:
code:
#include<stdio.h>
int GAM[5][5];
int X[5];
int n,m;
int print()
{
int i,j;
printf("THE COLOURS OF EACH NODE IS:");
printf("for node 1\t2\t3\t4\n");
for(i=1;i<=n;i++)
{
printf("%d",X[i]);
printf("\n");
}
}
int issafe( int k,int p)
{
int c;
for(c=1;c<k;c++)
{
if(X[c]==p && GAM[c][k]==1)
return 0;
}
return 1;
}
void graphcolor(int k,int m)
{
int p;
for(p=1;p<=m;p++)// p represents colour no
{
if(issafe(k,p))//checking if could be coloured or not
{
X[k]=p;
if(k==n)
print();
else
graphcolor(k+1,m);
}
}
}
int main()
{
printf("enter the number of nodes");
scanf("%d",&n);
printf("enter 1 if edge exists else 0");
int i,j;
for( i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
printf("edge %d->%d",i,j);
scanf("%d",&GAM[i][j]);
}
printf("enter number of colours available");
scanf("%d",&m);
graphcolor(1,m);
return 0;
}
Given a graph G (V,E) where V represents the vertices in the graph and E represents the edges in the graph . Given m different colours to colour the nodes in such a way that no two adjacent nodes are of same colour.
eg:
for the given graph
and given two colours yellow and red
there are two solutions possible:
code:
#include<stdio.h>
int GAM[5][5];
int X[5];
int n,m;
int print()
{
int i,j;
printf("THE COLOURS OF EACH NODE IS:");
printf("for node 1\t2\t3\t4\n");
for(i=1;i<=n;i++)
{
printf("%d",X[i]);
printf("\n");
}
}
int issafe( int k,int p)
{
int c;
for(c=1;c<k;c++)
{
if(X[c]==p && GAM[c][k]==1)
return 0;
}
return 1;
}
void graphcolor(int k,int m)
{
int p;
for(p=1;p<=m;p++)// p represents colour no
{
if(issafe(k,p))//checking if could be coloured or not
{
X[k]=p;
if(k==n)
print();
else
graphcolor(k+1,m);
}
}
}
int main()
{
printf("enter the number of nodes");
scanf("%d",&n);
printf("enter 1 if edge exists else 0");
int i,j;
for( i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
printf("edge %d->%d",i,j);
scanf("%d",&GAM[i][j]);
}
printf("enter number of colours available");
scanf("%d",&m);
graphcolor(1,m);
return 0;
}
steps involved ;
for solution 1:(solution two similar to this)
No comments:
Post a Comment