Vous êtes sur la page 1sur 2

GraphcolorTest.

java
import java.util.*;
class Graph
{
int g[][];
int v,e;
int visited[],x[],n;
void creategraph()
{
int a,b;
Scanner kbd=new Scanner(System.in);
System.out.print("Enter No. Of Vertices");
v=kbd.nextInt();
System.out.print("Enter No. Of Edges");
e=kbd.nextInt();
//create matrix of v+1 rows & v+1 cols
g=new int[v+1][v+1];
//initialize entire matrix g to zero
for (int i=1;i<=v;i++)
for (int j=1;j<=v;j++)
g[i][j]=0;
//store edge information
for (int i=1;i<=e;i++)
{
System.out.println("Enter Edge Information");
a=kbd.nextInt();
b=kbd.nextInt();
g[a][b]=g[b][a]=1;
}
}//end creategraph
void read()
{
//read no of colors & also make x array
Scanner kbd=new Scanner(System.in);
System.out.print("Enter no of colors");
n=kbd.nextInt();
x=new int[v+1];
}
boolean color(int k,int i)
{
for (int j=1;j<=k-1;j++)
{
if(g[k][j]!=0 && x[j]==i)
return false;
}
return true;
}
void graphcolor(int k)
{
for (int i=1;i<=n;i++)
{
if(color(k,i))
{
x[k]=i;
if(k==v)
{
//print solution
for (int j=1;j<=v;j++)
System.out.print(x[j]+" ");
System.out.println();
}
else
graphcolor(k+1);
}
Page 1
GraphcolorTest.java
}//end for
}//end graphcolor
}//end Graph class
public class GraphcolorTest
{
public static void main(String args[])
{
Graph g=new Graph();
g.creategraph();
g.read();
g.graphcolor(1);
}
}

Page 2

Vous aimerez peut-être aussi