Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include<iostream>

#include<cmath>
using namespace std;

//test function
bool test(int cross[], int x) {
// adjacent array
static int checkList[8][5] = {
{-1},
{0,-1},
{1,-1},
{0,1,2,-1},
{1,2,3,-1},
{2,4,-1},
{0,3,4,-1},
{3,4,5,6,-1},
};

// check if number is on grid already if yes it will return false of course


for (int i = 0; i < x; i++)
if (cross[x] == cross[i])
return false;

// checks if numbers next to the current num is consecutive if yes, return


false because it obv cannot be placed there
for (int i = 0; checkList[x][i] != -1; i++)
if (abs(cross[x] - cross[checkList[x][i]]) == 1)
return false;

// if numbers are not consecutive we return true


return true;
}

// print function
void print(int cross[], int cap) {
static int count = 0; // static because we want it to last for duration of
global scope in program
cout << " Solution number: " << ++count << endl;
// print the grid
cout << " " << cross[1] << cross[2] << endl;
cout << cross[0] << cross[3] << cross[4] << cross[5] << endl;
cout << " " << cross[6] << cross[7] << endl;
return;
}

int main()
{
int q[8] = {0};
int c = 0;
q[0] = 0;
while (c >= 0) { // first row in array
c++;
if (c == 8) //means u passed the last column
{
print(q, c); // Prints the solution!
c --;
if (c == -1)
{
return 0;
}
}
else //
{
q[c] = -1;
}
while (c >= 0) {
q[c]++;
if (q[c]== 8)// row is at 8 you back track because its passed the
last row already
{
c--;
if (c == -1)// you have gone over the array
{

return 0;
}
}
else
{
if (test(q, c)) // check if test func is accurate
break;
}
}
}

system("pause");
return 0;
}

You might also like