Question: Recursive Backtracking. Program any functional n-queens solution; N Queens is a very popular problem of backtracking algorithms in coding interviews. It was first proposed by

Recursive Backtracking. Program any functional n-queens solution; N Queens is a very popular problem of backtracking algorithms in coding interviews. It was first proposed by German chess enthusiast Max Bezzel in 1848. The problem means to place n queens on an n x n chessboard so that no queens attack each other. For readers unfamiliar with the rules of chess, this means that there are not two queens in the same row, column, or diagonal.

#include

using namespace std;

bool isSafe(int** arr, int x, int y, int n){

for(int row=0; row < x; row++){

if(arr[row][y]==1){

return false;

}

}

int row = x;

int col;

while(row >= 0 && col >=0){

if(arr[row][col]==1){

return false;

}

row--;

col--;

}

row = x;

col = y;

while(row >= 0 && col < n){

if(arr[row][col]==1){

return false;

}

row--;

col++;

}

return true;

}

bool nQueen(int** arr, int x, int n){

if(x >= n){

return true;

}

for(int col=0; col < n; col++){

if(isSafe(arr, x, col, n)){

arr[x][col]=1;

if(nQueen(arr, x+1, n)){

return true;

}

arr[x][col] = 0;

}

}

return false;

}

int main(){

int n;

cin>>n;

int** arr=new int*[n];

for(int i=0; i

arr[i]=new int[n];

for(int j=0; j

arr[i][j]=0;

}

}

if(nQueen(arr, 0, n)){

for(int i=0; i

for(int j=0; j

cout<

}cout<

}

}

return 0;

}

How would you propose augmenting the code to produce 5 queens? Explain with code. (C++)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!