Graph Coloring HamiltonianProblem
Graph Coloring HamiltonianProblem
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:
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.
#include <stdbool.h>
#include <stdio.h>
/* 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) */
/* 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.*/
// 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:
Illustrations:
Let’s find out the Hamiltonian cycle for the following graph:
As cycle is not found in path {0, 3, 1, 4, 2}. So, return from node 2, node 4.
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.
return 1;
}
printSolution (path);
return 1;
}
// Let us print the first vertex again to show the complete cycle
printf (" %d ", path[0]);
printf ("\n");
}
return 0;
}
Output:
Solution Exists: Following is one Hamiltonian Cycle
0 1 2 4 3 0