-
Notifications
You must be signed in to change notification settings - Fork 4
/
n-queen.cpp
71 lines (66 loc) · 899 Bytes
/
n-queen.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include<iostream>
#include<math.h>
using namespace std;
int board[30],count=0;
void queen(int);
int placeQueen(int);
void printSolution(int);
int main()
{
int i,n;
cout<<"Enter the number of Queens\n";
cin>>n;
queen(n);
cout<<"\nTotal solutions = "<<count;
return 0;
}
int placeQueen(int pos)
{
int i;
for(i=1;i<pos;i++)
{
if((board[i]==board[pos])||((abs(board[i]-board[pos])==abs(i-pos))))
return 0;
}
return 1;
}
void printSolution(int n)
{
int i,j;
count++;
cout<<"\n\nSolution["<<count<<"]:\n";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(board[i]==j)
cout<<"Q\t";
else
cout<<"*\t";
}
cout<<endl;
}
}
void queen(int n)
{
int k=1;
board[k]=0;
while(k!=0)
{
board[k]=board[k]+1;
while((board[k]<=n)&&!placeQueen(k))
board[k]++;
if(board[k]<=n)
{
if(k==n)
printSolution(n);
else
{
k++;
board[k]=0;
}
}
else
k--;
}
}