EIGHT QUEEN’S PROBLEM USING BACKTRACKING APPROACH ALGORITHM




#include<iostream.h>
#include<conio.h>
#include<math.h>
int x[10],count=0,true=1,false=0;
int place(int k,int i);

class queen
{
public:
void nqueens(int k,int n);
};

void queen::nqueens(int k,int n)
{
int i,j;
for(i=1;i<=n;i++)
{
if(place(k,i))
{
x[k]=i;
if(k==n)
{
for(j=1;j<=n;j++)
{
int zz;
for(zz=1;zz<=n;zz++)
{
if(x[j]==zz)
{
cout<<"Q";
count++;
}
else
{
cout<<"*";
}
}
cout<<"\n";
}
}
if(count==n)
{
return;
}
else
{
nqueens(k+1,n);
}
}
}
}

int place(int k,int i)
{
int j;
for(j=1;j<=k-1;j++)
{
if((x[j]==i||(abs(x[j]-i)==abs(j-k))))
return false;
}
return true;
}

void main()
{
int n;
clrscr();
queen obj;
cout<<"\n\t\t\tN-QUEENS PROBLEM";
cout<<"\nEnter the Number of Queens:";
cin>>n;
cout<<"\n\nThe Queens can be placed in positions as follows:\n\n";
obj.nqueens(1,n);
getch();
}




OUTPUT:
           
           
                        N-QUEENS PROBLEM

Enter the Number of Queens: 8


The Queens can be placed in positions as follows:

Q*******
****Q***
*******Q
*****Q**
**Q*****
******Q*
*Q******
***Q****

Comments

Popular posts from this blog

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE

BOOKS DETAILS USING C STRUCTURE

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE