Friday, 10 October 2014

Back Tracking - m coloring problem


#include<stdio.h>

//total vertices of ours graph
#define V 4

void printSol(int color[]);




// utility function to check whther assighning a color to vertex is safe
bool isSafe(int v, bool graph[V][V], int color[], int c)
{
    //check for adjacent vertices which dont have same color as 'c'
    for (int i = 0; i < V; ++i)
    {
        if (graph[v][i] && c == color[i])
            return false ;
    }
    return true;
}

//recursive util to solve m coloring prblm

bool graphColornUtil(bool graph[V][V], int m, int color[], int v)
{
    //base case if all vertices are colored
    if (v == V)
        return true;

    //consider all colors for this vertex v
    for (int c = 1; c <= m; ++c)
    {
        if (isSafe(v, graph, color,c))
        {
            color[v] = c;
            if (graphColornUtil(graph, m, color, v + 1) == true)
                return true;
            //backtrack
            color[v] = 0;

        }
    }

    return false; // if no color can be assighned
}


bool graphColoring(bool graph[V][V], int m)
{
    // Initialize all color values as 0. This initialization is needed
    // correct functioning of isSafe()
    int *color = new int[V];
    for (int i = 0; i < V; i++)
        color[i] = 0;

    // Call graphColoringUtil() for vertex 0
    if (graphColornUtil(graph, m, color, 0) == false)
    {
        printf("Solution does not exist");
        return false;
    }

    // Print the solution
    printSol(color);
    return true;
}

/* function to print solution */
void printSol(int color[])
{
    printf("Sol Exists:"
        " Following r the assigned colors \n");
    for (int i = 0; i < V; i++)
        printf(" %d ", color[i]);
    printf("\n");
}

// driver program to test above function
int main()
{
    /* Create following graph and test whether it is 3 colorable
    (3)---(2)
    |      /   |
    |    /     |
    | /       |
    (0)---(1)
    */

    //adjaceny matrix
    bool graph[V][V] = { { 0, 1, 1, 1 },
    { 1, 0, 1, 0 },
    { 1, 1, 0, 1 },
    { 1, 0, 1, 0 },
    };
    int m = 3; // Number of colors
    graphColoring(graph, m);
    getchar();
    return 0;
}

No comments:

Post a Comment