-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn queens
56 lines (47 loc) · 1 KB
/
n queens
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
#include <iostream>
#include <cmath>
using namespace std;
bool ok(int q[], int c) {
for(int i =0; i <c;i++){
if(q[c]==q[i] || (c-i)==abs(q[c]-q[i]))
return false;
}
return true;
}
int nqueens(int n) {
int* q = new int[n];
q[0] = 0;
int r = 0;
int c = 0;
static int solutions = 0;
while (c >= 0){
c++;
if(c > n){
solutions ++;
c--;
r = q[c]; }
else
r = -1;
while (c >= 0) {
r++;
q[c] = r;
if(r > n){
c --;
r = q[c];
}
else if(ok(q,c)){
break;
}
}
}
delete [] q;
return solutions;
}
int main() {
int n;
cout<<"Give me a number:"<<endl;
cin >> n;
for (int i = 0; i < n; ++i)
cout << "There are " << nqueens(i) << " solutions to the " << i+1 << " queens problem.\n";
return 0;
}