-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathK bishop
52 lines (49 loc) · 1.18 KB
/
K bishop
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
#include <iostream>
#include <cmath>
using namespace std;
bool ok(int q[], int c, int n) {
for (int i = 0; i < c; ++i)
if ((q[c]/n - q[i]/n) == abs(q[c]%n - q[i]%n))
return false;
return true;
}
// The function below is from a working n queens program.
// Add a 2nd parameter, k, and modify the function so that it will work for the k bishops program.
// You will have to change the board representation,
// the conditions for when you've found a solution and when to backtrack, and the ok function call.
int nqueens(int n) {
int* q = new int[n];
q[0] = 0;
int c = 0, solutions = 0;
while (c >= 0) {
++c;
if (c == n) {
++solutions;
--c;
}
else
q[c] = -1;
while (c >= 0) {
++q[c];
if (q[c] == n)
--c;
else if (ok(q, c))
break;
}
}
delete[] q;
return solutions;
}
int main() {
int n, k;
while (true) {
cout << "Enter value of n: ";
cin >> n;
if (n == -1)
break;
cout << "Enter value of k: ";
cin >> k;
cout << "number of solutions: " << kbishops(n, k) << "\n";
}
return 0;
}