Ai 4
Ai 4
15
Code :
N Queen Problem using Branch And Bound
#include<bits/stdc++.h>
int N;
void printSol(vector<vector<int>>board)
for(int i = 0;i<N;i++){
for(int j = 0;j<N;j++){
cout<<board[i][j]<<" ";
cout<<"\n";
isSafe function to check if current row contains or current left diagonal or current right diagonal
contains any queen or not if
*/
bool isSafe(int row ,int col ,vector<bool>rows ,
vector<bool>left_digonals ,vector<bool>Right_digonals)
return false;
return true;
if(col>=N){
return true;
for(int i = 0;i<N;i++)
if(isSafe(i,col,rows,left_digonals,Right_digonals) == true)
rows[i] = true;
left_digonals[i+col] = true;
Right_digonals[col-i+N-1] = true;
if(solve(board,col+1,rows,left_digonals,Right_digonals) == true){
return true;
// Backtracking
rows[i] = false;
left_digonals[i+col] = false;
Right_digonals[col-i+N-1] = false;
return false;
int main()
cin>>N;
vector<vector<int>>board(N,vector<int>(N,0));
vector<bool>rows(N,false);
vector<bool>left_digonals(2*N-1,false);
vector<bool>Right_digonals(2*N-1,false);
if(ans == true){
printSol(board);
else{
}
Output :
Code :
M Coloring problem using backtracking
#include <bits/stdc++.h>
#define V 4
vertices(i-->adj vertices) or
return false;
return true;
int v)
if (v == V)
return true;
c to v is fine*/
color[v] = c;
/* recur to assign colors to
if (graphColoringUtil(graph, m, color, v + 1)
== true)
return true;
color[v] = 0;
return false;
feasible solutions.*/
int color[V];
color[i] = 0;
return false;
printSolution(color);
return true;
}
/* A utility function to print solution */
<< "\n";
// Driver code
int main()
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 },
};
// Number of colors
int m = 3;
// Function call
graphColoring(graph, m);
return 0;
}
Output :