C - Program to Implement N - Queens Problem (Recursive Solution)
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<time.h>
class queen
{
public:
int x[20],count;
void nqueen(int,int);
int place(int,int);
void write(int x[],int);
};
int main()
{
int i,n;
char k='y';
queen q;
do
{
clrscr();
float toc;
clock_t end,start;
start=clock();
cout<<"\n\t\t\t N-Queens Problem";
cout<<"\n\t\t\t------------------";
cout<<"\n\n\t\tEnter Size of Chessboard :: ";
cin>>n;
q.count=0;
q.nqueen(1,n);
cout<<"\n\t\tTotal No of Solutions ::"<<q.count;
end=clock();
toc=(end - start)/CLK_TCK;
cout<<"\n\t\tTime Complexity :: "<<toc;
cout<<"\n\t\tDo you want to continue?(y/n)";
k=getche();
}while(k=='y');
return 0;
}
void queen::nqueen(int k,int n)
{
int i;
for(i=1;i<=n;i++)
{
if(place(k,i))
{
x[k]=i;
if(k==n)
write(x,n);
else
nqueen(k+1,n);
}
}
}
int queen::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 0;
}
return 1;
}
void queen::write(int x[],int n)
{
int i,j;
cout<<"\n\n\t\t"<<count+1<<") Possible Solution :: ";
for(i=1;i<=n;i++)
{
cout<<" "<<x[i];
}
cout<<"\n";
for(i=1;i<=n;i++)
{
cout<<"\n\t\t\t";
for(j=1;j<=n;j++)
{
if(j==x[i])
cout<<" Q ";
else
cout<<" x ";
}
}
cout<<"\n\n";
count++;
}
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<time.h>
class queen
{
public:
int x[20],count;
void nqueen(int,int);
int place(int,int);
void write(int x[],int);
};
int main()
{
int i,n;
char k='y';
queen q;
do
{
clrscr();
float toc;
clock_t end,start;
start=clock();
cout<<"\n\t\t\t N-Queens Problem";
cout<<"\n\t\t\t------------------";
cout<<"\n\n\t\tEnter Size of Chessboard :: ";
cin>>n;
q.count=0;
q.nqueen(1,n);
cout<<"\n\t\tTotal No of Solutions ::"<<q.count;
end=clock();
toc=(end - start)/CLK_TCK;
cout<<"\n\t\tTime Complexity :: "<<toc;
cout<<"\n\t\tDo you want to continue?(y/n)";
k=getche();
}while(k=='y');
return 0;
}
void queen::nqueen(int k,int n)
{
int i;
for(i=1;i<=n;i++)
{
if(place(k,i))
{
x[k]=i;
if(k==n)
write(x,n);
else
nqueen(k+1,n);
}
}
}
int queen::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 0;
}
return 1;
}
void queen::write(int x[],int n)
{
int i,j;
cout<<"\n\n\t\t"<<count+1<<") Possible Solution :: ";
for(i=1;i<=n;i++)
{
cout<<" "<<x[i];
}
cout<<"\n";
for(i=1;i<=n;i++)
{
cout<<"\n\t\t\t";
for(j=1;j<=n;j++)
{
if(j==x[i])
cout<<" Q ";
else
cout<<" x ";
}
}
cout<<"\n\n";
count++;
}