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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#include <iostream>
#include <stdlib.h>
using namespace std;
//All the necessary functions
void nextRow(int[],int);
void backtrack(int[],int);
void print(int[],int);
bool ok(int[],int);
int q[8];
int c;
int main()
{
//This is the counter to effectively progress through the loop. the "flag" of the program.
int counter;
c = 0;
q[0] = 0;
counter = 2;
while(c > -1)
{
c++;
counter--;
if(c == 8){
print(q,c);
counter++;
}
if(counter == 1){
q[c] = -1;
nextRow(q,c);
}
}
return 0;
}
//This increments the row of the current column you are on, and if
the row is equal to 8, it knows to backtrack and try the next row in the
previous column.
void nextRow(int q[],int c)
{
q[c]++;
if(q[c] == 8)
backtrack(q,c);
ok(q,c);
}
//This is the test to see whether or not you can put a queen in that position.
bool ok(int q[],int c)
{
for(int i = 0; i < c; i++)
{
if(q[c] == q[i] || abs(q[c] - q[i]) == abs(c - i))
nextRow(q,c);
}
}
//Sets the current row equal to zero and goes back to the previous column
to increment the row.
void backtrack(int q[],int c)
{
q[c] = 0;
c--;
if(c == -1)
exit(0);
nextRow(q,c);
}
//Goes to the print function when c = 8.
void print(int q[],int c)
{
for(int i = 0; i < 8; i++)
{
cout << q[i];
}
cout << endl;
backtrack(q,c);
}
|