-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathN Queens.cpp
49 lines (41 loc) · 907 Bytes
/
N Queens.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
#include <iostream>
using namespace std;
bool ok(int q[], int c) {
for(int i=1;i<=c;i++)
if (q[c]==q[i-1] || q[c]-i==q[c-i] || q[c]+i==q[c-i])
return false;
return true;
}
// This function should return the number of solutions for the given board size.
int nqueens(int n) {
int *a;
a= new (nothrow) int[n];
for(int i=0;i<n;i++) a[i]=0;
int c=0,r=0,solutions=0;
while (c >= 0) {
++c;
if(c>=n){
++solutions;
--c;
r=a[c];
}
else r=-1;
while (c >= 0) {
++r;
a[c]=r;
if(r>=n){
--c;
r=a[c];
}
else if(ok(a,c)) break;
}
}
delete []a;
return solutions;
}
int main() {
int n = 12;
for (int i = 1; i <= n; ++i)
cout << "There are " << nqueens(i) << " solutions to the " << i << " queens problem.\n";
return 0;
}