97 lines
2.4 KiB
C#
97 lines
2.4 KiB
C#
using System;
|
|
using System.Threading.Tasks;
|
|
|
|
class GraphColoringProblem
|
|
{
|
|
// Number of vertices in the graph
|
|
const int V = 4;
|
|
|
|
// A utility function to check if the current color assignment is safe for vertex v
|
|
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;
|
|
}
|
|
|
|
// A parallel utility function to solve m coloring problem
|
|
static bool GraphColoringUtilParallel(bool[,] graph, int m, int[] color, int v)
|
|
{
|
|
if (v == V)
|
|
return true;
|
|
|
|
bool result = false;
|
|
|
|
Parallel.For(1, m + 1, (c, state) =>
|
|
{
|
|
if (IsSafe(v, graph, color, c))
|
|
{
|
|
color[v] = c;
|
|
|
|
if (GraphColoringUtilParallel(graph, m, color, v + 1))
|
|
{
|
|
result = true;
|
|
state.Break(); // Exit parallel loop as a solution is found
|
|
}
|
|
if (result == false)
|
|
color[v] = 0; // Backtrack
|
|
}
|
|
});
|
|
|
|
return result;
|
|
}
|
|
|
|
// This function solves the m Coloring problem using parallelism
|
|
static bool SolveGraphColoring(bool[,] graph, int m)
|
|
{
|
|
int[] color = new int[V];
|
|
for (int i = 0; i < V; i++)
|
|
color[i] = 0;
|
|
|
|
if (!GraphColoringUtilParallel(graph, m, color, 0))
|
|
{
|
|
Console.WriteLine("Solution does not exist");
|
|
return false;
|
|
}
|
|
|
|
PrintSolution(color);
|
|
return true;
|
|
}
|
|
|
|
// A utility function to print solution
|
|
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();
|
|
}
|
|
|
|
// Driver code
|
|
static void Main(string[] args)
|
|
{
|
|
/* Create following graph and test whether it is 3 colorable
|
|
(3)---(2)
|
|
| / |
|
|
| / |
|
|
| / |
|
|
(0)---(1)
|
|
*/
|
|
bool[,] graph = {
|
|
{ false, true, true, true },
|
|
{ true, false, true, false },
|
|
{ true, true, false, true },
|
|
{ true, false, true, false }
|
|
};
|
|
|
|
// Number of colors
|
|
int m = 3;
|
|
|
|
// Function call
|
|
SolveGraphColoring(graph, m);
|
|
}
|
|
}
|