0% found this document useful (0 votes)
39 views10 pages

Graph Coloring HamiltonianProblem

The document discusses using backtracking algorithms to solve graph coloring and Hamiltonian cycle problems. It provides explanations of the approaches with illustrations and includes Python code implementations for coloring a graph with a minimum number of colors and finding a Hamiltonian cycle.

Uploaded by

Labanya Saha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views10 pages

Graph Coloring HamiltonianProblem

The document discusses using backtracking algorithms to solve graph coloring and Hamiltonian cycle problems. It provides explanations of the approaches with illustrations and includes Python code implementations for coloring a graph with a minimum number of colors and finding a Hamiltonian cycle.

Uploaded by

Labanya Saha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

M-Coloring Issue with Retracing:

Beginning with vertex 0, give each vertice a different color. Before assigning a color, check
for safety by considering the already given colors to the neighboring vertices i.e. check if the
nearby vertices have the same color or not. If any colour assignment does not contradict the
criteria, mark the color assignment as part of the solution. If assigning a colour is not feasible,
return and return false.
Follow the given steps to solve the problem:
 Create a recursive function that takes the graph, current index, number of vertices, and
color array.
 If the current index is equal to the number of vertices. Print the color configuration in
the color array.
 Assign a color to a vertex from the range (1 to m).
 For every assigned color, check if the configuration is safe, (i.e. check if the adjacent
vertices do not have the same color) and recursively call the function with the next
index and number of vertices otherwise, return false
 If any recursive function returns true then return true
 If no recursive function returns true then return false

Illustration:

 To color the graph, color each node one by one.


 To color the first node there are 3 choices of colors Red, Green and Blue, so lets take
the red color for first node.
 After Red color for first node is fixed then we have made choice for second node in
similar manner as we did for first node, then for 3rd node and so on.
 There is one important point to remember. while choosing color for the node, it should
not be same as the color of the adjacent node.

Choosing Red For Node 1


 As shown in the above diagram, all the solutions are shown by coloring the first node
in Red.
 Let’s choose Green color for the first node and explore the options for the remaining
nodes.

Choosing Green for Node 1

 As shown in the above diagram, all the solutions are shown by coloring the first node
in Green.
 Let’s choose Blue color for the first node and explore the options for the remaining
nodes.

Choosing Blue for Node 1


Below is the implementation of the above approach:
// C program for solution of M
// Coloring problem using backtracking

#include <stdbool.h>
#include <stdio.h>

// Number of vertices in the graph


#define V 4

void printSolution(int color[]);

/* A utility function to check if the current color assignment is safe for vertex v i.e. checks whether the edge exists or not
(i.e, graph[v][i]==1). If exist then checks whether the color to be filled in the new vertex(c is sent in the parameter) is
already used by its adjacent vertices(i-->adj vertices) or not (i.e, color[i]==c) */

bool isSafe(int v, bool graph[V][V], int color[], int c)


{
for (int i = 0; i < V; i++)
if (graph[v][i] && c == color[i])
return false;
return true;
}

/* A recursive utility function


to solve m coloring problem */
bool graphColoringUtil(bool graph[V][V], int m, int color[],
int v)
{
/* base case: If all vertices are
assigned a color then return true */
if (v == V)
return true;

/* Consider this vertex v and


try different colors */
for (int c = 1; c <= m; c++) {
/* Check if assignment of color
c to v is fine*/
if (isSafe(v, graph, color, c)) {
color[v] = c;

/* recur to assign colors to


rest of the vertices */
if (graphColoringUtil(graph, m, color, v + 1)
== true)
return true;

/* If assigning color c doesn't


lead to a solution then remove it */
color[v] = 0;
}
}

/* If no color can be assigned to


this vertex then return false */
return false;
}

/* This function solves the m Coloring problem using Backtracking. It mainly uses graphColoringUtil() to solve the problem.
It returns false if the m colors cannot be assigned, otherwise returns true and prints assignments of colors to all vertices.
Please note that there may be more than one solution, this function prints one of the feasible solutions.*/

bool graphColoring(bool graph[V][V], int m)


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

// Call graphColoringUtil() for vertex 0


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

// Print the solution


printSolution(color);
return true;
}

/* A utility function to print solution */


void printSolution(int color[])
{
printf("Solution Exists:"
" Following are the assigned colors \n");
for (int i = 0; i < V; i++)
printf(" %d ", color[i]);
printf("\n");
}

// Driver code
int main()
{
/* Create following graph and test
whether it is 3 colorable
(3)---(2)
|/|
|/|
|/|
(0)---(1)
*/
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

// Function call
graphColoring(graph, m);
return 0;
}

Output:

Solution Exists: Following are the assigned colors


1 2 3 2

Utilizing the Backtracking Algorithm for the Hamiltonian Cycle:


Add vertex 0 to an empty path array that has been created. Adding more vertices should begin
with vertex 1. Verify that a vertex is not been added and that it is next to one that has already
been inserted before adding it. In the event that such a vertex is located, it is included in the
solution. We return false in the event that no vertex is found.

Illustrations:

Let’s find out the Hamiltonian cycle for the following graph:

 Start with the node 0 .


 Apply DFS for finding the Hamiltonian path.
 When base case reach (i.e. total no of node traversed == V (total vertex)):
 Check whether current node is a neighbour of starting node.
 As node 2 and node 0 are not neighbours of each other so return from it.

Starting from start node 0 calling DFS

 As cycle is not found in path {0, 3, 1, 4, 2}. So, return from node 2, node 4.

 Now, explore another option for node 1 (i.e node 2)


 When it hits the base condition again check for Hamiltonian cycle
 As node 4 is not the neighbour of node 0, again cycle is not found then return.
 Return from node 4, node 2, node 1.

 Now, explore other options for node 3.

Hamiltonian Cycle
 In the Hamiltonian path {0,3,4,2,1,0} we get cycle as node 1 is the neighbour of
node 0.
 So print this cyclic path .
 This is our Hamiltonian cycle.

The following is the implementation of backtracking to locate the Hamiltonian cycle:


/* C program for solution of Hamiltonian Cycle problem
using backtracking */
#include<stdio.h>

// Number of vertices in the graph


#define V 5

void printSolution (int path[]);

/* A utility function to check if the vertex v can be added at


index 'pos' in the Hamiltonian Cycle constructed so far (stored
in 'path[]') */
int
isSafe (int v, int graph[V][V], int path[], int pos)
{
/* Check if this vertex is an adjacent vertex of the previously
added vertex. */
if (graph[path[pos - 1]][v] == 0)
return 0;

/* Check if the vertex has already been included.


This step can be optimized by creating an array of size V */
for (int i = 0; i < pos; i++)
if (path[i] == v)
return 0;

return 1;
}

/* A recursive utility function to solve hamiltonian cycle problem */


int
hamCycleUtil (int graph[V][V], int path[], int pos)
{
/* base case: If all vertices are included in Hamiltonian Cycle */
if (pos == V)
{
// And if there is an edge from the last included vertex to the
// first vertex
if (graph[path[pos - 1]][path[0]] == 1)
return 1;
else
return 0;
}

// Try different vertices as a next candidate in Hamiltonian Cycle.


// We don't try for 0 as we included 0 as starting point in hamCycle()
for (int v = 1; v < V; v++)
{
/* Check if this vertex can be added to Hamiltonian Cycle */
if (isSafe (v, graph, path, pos))
{
path[pos] = v;

/* recur to construct rest of the path */


if (hamCycleUtil (graph, path, pos + 1) == 1)
return 1;

/* If adding vertex v doesn't lead to a solution,


then remove it */
path[pos] = -1;
}
}

/* If no vertex can be added to Hamiltonian Cycle constructed so far,


then return false */
return 0;
}

/* This function solves the Hamiltonian Cycle problem using Backtracking.


It mainly uses hamCycleUtil() to solve the problem. It returns false
if there is no Hamiltonian Cycle possible, otherwise return true and
prints the path. Please note that there may be more than one solutions,
this function prints one of the feasible solutions. */
int
hamCycle (int graph[V][V])
{
int path[V];
for (int i = 0; i < V; i++)
path[i] = -1;

/* Let us put vertex 0 as the first vertex in the path. If there is


a Hamiltonian Cycle, then the path can be started from any point
of the cycle as the graph is undirected */
path[0] = 0;
if (hamCycleUtil (graph, path, 1) == 0)
{
printf ("\nSolution does not exist");
return 0;
}

printSolution (path);
return 1;
}

/* A utility function to print solution */


void
printSolution (int path[])
{
printf ("Solution Exists:" " Following is one Hamiltonian Cycle \n");
for (int i = 0; i < V; i++)
printf (" %d ", path[i]);

// Let us print the first vertex again to show the complete cycle
printf (" %d ", path[0]);
printf ("\n");
}

// driver program to test above function


int
main ()
{
/* Let us create the following graph
(0)--(1)--(2)
| /\ |
| / \ |
|/ \|
(3)-------(4) */
int graph1[V][V] = { {0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};

// Print the solution


hamCycle (graph1);

/* Let us create the following graph


(0)--(1)--(2)
| /\ |
| / \ |
|/ \|
(3) (4) */
int graph2[V][V] = { {0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
};

// Print the solution


hamCycle (graph2);

return 0;
}

Output:
Solution Exists: Following is one Hamiltonian Cycle
0 1 2 4 3 0

Solution does not exist

You might also like