using
System;
class
GraphColoringProblem
{
const
int
V = 4;
static
bool
IsSafe(
int
v,
bool
[,] graph,
int
[] color,
int
c)
{
for
(
int
i = 0; i < V; i++)
{
if
(graph[v, i] && c == color[i])
return
false
;
}
return
true
;
}
static
bool
GraphColoringUtil(
bool
[,] graph,
int
m,
int
[] color,
int
v)
{
if
(v == V)
return
true
;
for
(
int
c = 1; c <= m; c++)
{
if
(IsSafe(v, graph, color, c))
{
color[v] = c;
if
(GraphColoringUtil(graph, m, color, v + 1))
return
true
;
color[v] = 0;
}
}
return
false
;
}
static
bool
SolveGraphColoring(
bool
[,] graph,
int
m)
{
int
[] color =
new
int
[V];
for
(
int
i = 0; i < V; i++)
color[i] = 0;
if
(!GraphColoringUtil(graph, m, color, 0))
{
Console.WriteLine(
"Solution does not exist"
);
return
false
;
}
PrintSolution(color);
return
true
;
}
static
void
PrintSolution(
int
[] color)
{
Console.WriteLine(
"Solution Exists: Following are the assigned colors"
);
for
(
int
i = 0; i < V; i++)
Console.Write(
" "
+ color[i] +
" "
);
Console.WriteLine();
}
static
void
Main(
string
[] args)
{
bool
[,] graph = {
{
false
,
true
,
true
,
true
},
{
true
,
false
,
true
,
false
},
{
true
,
true
,
false
,
true
},
{
true
,
false
,
true
,
false
}
};
int
m = 3;
SolveGraphColoring(graph, m);
}
}