-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8queens1D_nogotos.cpp
60 lines (53 loc) · 1.42 KB
/
8queens1D_nogotos.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
// Shimon Savitsky 8 queens 1D without GOTO's
/*****
Ceate a bool funtion to judge is the array is valid, Use
a print funtion to print when ever a solution is found, and
use a backtrack funtion to backtrack the column (if it reaches -1
then there are no more solutions). In the main funtion there should be
a nexted while loop that will continue as long as the column is
above or equale to zero. If the it gets to the last column then it should
print and backtrack to find another solution. Otherwise, it should
start from the begining of the next row. this should loop until ALL
solutions are found.
*****/
#include <iostream>
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;
}
void print(int q[], int &counter) {
counter++;
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
if (q[c] == r) cout << "1" << " ";
else cout << "0" << " ";
}
cout << endl;
}
cout << "Solution #" << counter << endl;
}
void backtrack(int &c) {
c--;
if (c == -1) exit(0);
}
int main () {
int c = 0, counter = 0, q[8];
q[0] = 0;
while (c != -1) {
c++; // NC
if (c == 8) {
print(q, counter);
backtrack(c);
}
else q[c] = -1;
while (c != -1) {
q[c]++;
if (q[c] == 8) backtrack(c);
else if (ok(q, c) == true) break;
}
}
return 0;
}