Posts tagged ‘queen’

February 1, 2011

Queen’s puzzle. C++ Programming code


#include <iostream.h>
const short int maxqn=20;
int solnum=0,x[maxqn+1];
bool raw[maxqn+1],md[maxqn*2],sd[maxqn*2+1],found=1;
//short int j=0;

void printsolution(int qn)
{
for(int l=1;l<=qn;l++)
{
cout<<x[l]<<“t”;
}
}

void try_first(short i,int qn)
{
short j=0;
do
{
j++;
if(raw[j]==true&&md[i-j+qn]==true&&sd[i+j]==true)
{
x[i]=j;
raw[j]=md[i-j+qn]=sd[i+j]=false;
if(i<qn) try_first(i+1,qn);
else {printsolution(qn);return;}
raw[j]=md[i-j+qn]=sd[i+j]=true;
}
}while(j<qn);

}
void try_all(int i,int qn)
{
short int j=0;
for(j=1;j<=qn;j++)
{
if(raw[j]&&md[i-j+qn]&&sd[i+j])
{
x[i]=j;
raw[j]=md[i-j+qn]=sd[i+j]=false;
if(i<qn) try_all(i+1,qn);
else {printsolution(qn);cout<<“n”;}
raw[j]=md[i-j+qn]=sd[i+j]=true;}
}

}
void main()
{
int qn,a=1;
do
{ cout<<“Number of Queens: “;
cin>>qn;
}while(qn<3||qn>maxqn);
for(int i=0;i<=maxqn;i++)
raw[i]=true;
for(int f=0;f<2*maxqn;f++)
md[f]=true;
for(int s=0;s<=2*maxqn;s++)
sd[s]=true;
try_first(a,qn);
cout<<“nn”;
try_all(a,qn);
}

Advertisements