Header Ad

HackerEarth N-Queens problem solution

In this HackerEarth N-Queens problem solution, we have given a chessboard having N x N cells, you need to place N queens on the board in such a way that no queen attacks any other queen.


HackerEarth N-Queens problem solution


HackerEarth N-Queens problem solution.

#include<bits/stdc++.h>

using namespace std;
int mat[110][110]={0};
int n;
int state=0;
int attacked(int x, int y){
if(mat[x][y])return 1;
for(int i=1; i<=n; i++){

if(y-i >= 1 && mat[x][y-i])return 1;
if(y+i <= n && mat[x][y+i])return 1;
if(x-i >= 1 && mat[x-i][y])return 1;
if(x+i <= n && mat[x+i][y])return 1;
if(x-i >= 1 && y-i >= 1 && mat[x-i][y-i])return 1;
if(x+i <= n && y+i <= n && mat[x+i][y+i])return 1;
if(x+i <= n && y-i >= 1 && mat[x+i][y-i])return 1;
if(x-i >= 1 && y+i <= n && mat[x-i][y+i])return 1;
}
return 0;
}

void print(){
cout<<endl;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}

int solve(int x){
if(x == 0){
print();
return 1;
}
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
if(attacked(i, j) == 1)continue;
mat[i][j] = 1;
if(solve(x-1))return 1;
mat[i][j] = 0;
}
}
return 0;
}

int main(){
cin>>n;
if(solve(n))
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
else
cout<<"Not possible\n";
return 0;
}


Post a Comment

0 Comments