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 <cmath>
using namespace std;
bool ok(int a[], int pos, int h[][5]);
void backtrack(int &c);
void print(int a[]);
//below is how I label the cross(1D array)
/*
1 2
0 3 4 5
6 7
*/
int main(){
int board[8]={0}, c=1;
int refer[8][5]={{-1,-1,-1,-1,-1},{0,-1,-1,-1,-1},{1,-1,-1,-1,-1},{0,1,2,-1,-1},{1,2,3,-1,-1},{2,4,-1,-1,-1},{0,3,4,-1,-1},{3,4,5,6,-1}}; //helper array tells me which box I shoud check depend on how I label the cross
board[0]=1; //we start with 1 in the zero index of the cross
while (c<9)
{
if(c==8) //the 1d array' max index is 7, if index=8 means we have a solution, print it
{
print(board);
return 0;
}
while(board[c]<10) //set the value in each box does not exceed 9, include 9, because we want to check if it fail to put
{ //a 8 in it.
board[c]++; //each time the box fails the check, we increment it by 1
if(board[c]==9) //till the value of the box becomes 9, and we proceed to backtrack
{
board[c]=0; //we first zero the current box
backtrack(c); //then go to the previous box and continue to increment the previous box's value
continue;
}
if(ok(board, c, refer)) //if the passed, means the value in this box doesn't conflict with surrounding box
break; //then we out of the loop and go to next box
}//while(board[c]<10
c++;
}//while(c<9)
}//main()
void backtrack(int &c)
{
c--;
}
bool ok(int a[], int pos, int h[][5])
{
for(int i=0; i<pos; i++)
{
if(a[pos]==a[i])
return false;
}
for(int j=0; j<4; j++)
{
if(h[pos][j]==-1)
return false;
if(abs(a[pos]-a[h[pos][j]])==1)
return false;
}
return true;
}
void print(int a[]){
cout<<" " <<a[1] <<a[2] <<endl <<a[0] <<a[3] <<a[4] <<a[5] <<endl <<" " <<a[7] <<a[8] <<" " <<endl;
}
|