Backtracking (Nqueen, Sum of Subsets, Graph Coloring), C2 - 26
Backtracking (Nqueen, Sum of Subsets, Graph Coloring), C2 - 26
Lab-10
Name- Manuja Joshi
Gr. No: 11910355
Division: ET-C
Roll No. : 26
Algorithm-
bool nqueen(int **arr,int x,int n){
if(x>=n){
return true;
}
for(int i=0; i<n;i++){
if(issafe(arr,x,i,n)){ // to check queen is not getting attacked
arr[x][i]=1;
if(nqueen(arr,x+1,n)){
return true;
}
arr[x][i]=0; //backtrack step
}
}
return false;
}
OUTPUT-
For n=6 , 1 shows the placement of n queens in n rows-
In this problem, there is a given set with some integer elements. And another
some value is also provided, we have to find a subset of the given set whose
sum is the same as the given sum value.
Here backtracking approach is used for trying to select a valid subset when an
item is not valid, we will backtrack to get the previous subset and add another
element to get the solution.
Input:
OUTPUT-
Graph Coloring problem using Backtracking -
In this problem, an undirected graph is given. There is also provided m colors.
The problem is to find if it is possible to assign nodes with m different colors,
such that no two adjacent vertices of the graph are of the same colors. If the
solution exists, then display which color is assigned on which vertex.
Starting from vertex 0, we will try to assign colors one by one to different
nodes. But before assigning, we have to check whether the color is safe or not.
A color is not safe whether adjacent vertices are containing the same color.
Input :
m=3 colours , 4 vertices
graph[V][V] = {
{0, 1, 1, 1},
{1, 0, 1, 0},
{1, 1, 0, 1},
{1, 0, 1, 0},}
Output : Assigned Colors are:
1232
Algorithm-
bool graphColoring(int colors, int color[], int vertex) {
if (vertex == V)
return true;
bool checkSolution(int m) {
int *color = new int[V]; //make color matrix for each vertex
OUTPUT-