N-Queen problem using Backtracking |C++
By Ujjal Roy
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
const ll N=100;
ll n;
ll arr[N][N];
bool is_safe(ll row,ll col)
{
for(ll i=0;i<n;i++)
{
if(arr[i][col]==1)return false;
}
ll x,y;
x=row;
y=col;
while(x>=0&&y>=0)
{
if(arr[x][y]==1)return false;
x--;
y--;
}
x=row;
y=col;
while(x>=0&&y<0)
{
if(arr[x][y]==1)return false;
x--;
y++;
}
return true;
}
bool is_ok(ll row)
{
if(row>=n)return true;
for(ll col=0;col<n;col++)
{
if(is_safe(row,col))
{
arr[row][col]=1;
if(is_ok(row+1))
{
return true;
}
else arr[row][col]=0;
}
}
return false;
}
int main()
{
ll i,j;
cout<<"Enter N : ";
cin>>n;
if(is_ok(0))
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)cout<<arr[i][j]<<" ";
cout<<endl;
}
}
return 0;
}
0 Comments