For some input of n such as 9 output seems to be coming wrong.
#include
using namespace std;
bool isSafe(int board[][10],int i,int j,int n)
{
//coln
for(int row=0;row<i;row++)
{
if(board[row][j]==1)
return false;
}
int x=i;
int y=j;
// left diagonal
while(x>=0 && y>=0)
{
if(board[x][y]==1)
return false;
x--;
y--;
}
// right diagonal
x=i;
y=j;
while(x>=0 && y<n)
{
if(board[x][y]==1)
return false;
x--;
y--;
}
return true;
}
bool solveNQueen(int board[][10],int i,int n)
{
if(i==n)
{
for(i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(board[i][j]==1)
cout<<" Q ";
else
cout<<" _ ";
}
cout<<endl;
}
cout<<endl;
return true;
}
for(int j=0;j<n;j++)
{
if(isSafe(board,i,j,n))
{
board[i][j]=1;
bool queenRakhPaaye=solveNQueen(board,i+1,n);
if(queenRakhPaaye)
{
return true;
}
board[i][j]=0;
}
}
return false;
}
int main()
{
int board[10][10]={0};
int n;
cin>>n;
solveNQueen(board,0,n);
}