#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
#include <stdio.h>
#include <stdlib.h>
#include <graphics.h>
const m=20;
int k[m][m];
void apply(int,int);
void remove(int,int);
void draw(void);
void move(int i,int j);
void check(void);
void setgraph(void);
int count=0,v,n,i,j,state;
void main()
{
cout<<" n-Queen \n\n";
cout<<"Size of board Board:";
cin>>n;
cout<<"how much Queen:";
cin>>v;
clrscr();
setgraph();
draw();
for (i=0;i<n;i++)
for (j=0;j<n;j++)
move(i,j);
getch();
closegraph();
}
void move(int p,int q)
{
apply(p,q);
check();
for (int i=p;i<n;i++)
for (int j=0;j<n;j++)
if (k[i][j]==0)
move(i,j);
remove(p,q);
}
void apply(int i,int j)
{
int p,q;
k[i][j]=1;
count++;
for (p=0;p<n;p++)
if (p!=i)
k[p][j]++;
for (p=0;p<n;p++)
if (p!=j)
k[i][p]++;
p=i+1;q=j+1;
while(p<n && q<n)
k[p++][q++]++;
p=i-1;q=j-1;
while(p>=0 && q>=0)
k[p--][q--]++;
p=i+1;q=j-1;
while(p<n && q>=0)
k[p++][q--]++;
p=i-1;q=j+1;
while(p>=0 && q<n)
k[p--][q++]++;
}
void remove(int i,int j)
{
int p,q;
k[i][j]=0;
count--;
for (p=0;p<n;p++)
if (p!=i)
k[p][j]--;
for (p=0;p<n;p++)
if (p!=j)
k[i][p]--;
p=i+1;q=j+1;
while(p<n && q<n)
k[p++][q++]--;
p=i-1;q=j-1;
while(p>=0 && q>=0)
k[p--][q--]--;
p=i+1;q=j-1;
while(p<n && q>=0)
k[p++][q--]--;
p=i-1;q=j+1;
while(p>=0 && q<n)
k[p--][q++]--;
}
void check (void)
{
if(count==v)
{
state++;
draw();
cout<<endl<<endl<<"press 0 to exit or any key to continue...";
int c=getch();
if (c=='0')
exit(0);
}
}
/*
void draw (void)
{
clrscr();
for (int p=0;p<n;p++)
{
for (int q=0;q<n;q++)
if (k[p][q]!=1)
cout<<'.'<<setw(3);
else
cout<<"X"<<setw(3);
cout<<endl<<endl;
}
cout<<"\n\n total states founded for "<< n <<"*" << n <<" boards and " << v <<" Queens : "<<state;
}
*/
void draw (void)
{
clrscr();
int mx=getmaxx()/m;
int my=getmaxy()/m;
for (int p=0;p<n;p++)
{
for (int q=0;q<n;q++)
{
if(k[p][q]==1)
{
setcolor(WHITE);
setfillstyle(1,YELLOW);
}
else
{
setcolor(WHITE);
setfillstyle(1,BLUE);
}
bar(p*mx+2,q*my+2,p*mx+mx+2,q*my+my+2);
rectangle(p*mx+2,q*my+2,p*mx+mx+2,q*my+my+2);
}
}
setcolor(WHITE);
rectangle(2,2,mx*n+2,my*n+2);
rectangle(0,0,mx*n+4,my*n+4);
gotoxy(2,25);
cout<<"\n\n total states founded for "<< n <<"*" << n <<" boards and " << v <<" Queens : "<<state;
}
void setgraph(void)
{
int gd=DETECT, gm;
initgraph (&gd,&gm,"..\\bgi");
}