如下的10个格子
+--+--+--+
| | | |
+--+--+--+--+
| | | | |
+--+--+--+--+
| | | |
+--+--+--+
填入0~9的数字。要求:连续的两个数字不能相邻。(左右、上下、对角都算相邻)
一共有多少种可能的填数方案?
#include <iostream>
#include <cstring>
using namespace std;
int thearray[10];
int record[10] = {0};
int conflict[10][10] = {
0, 1, 0, 0, 1, 1, 1, 0, 0, 0,
1, 0, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 1, 1, 0, 0, 0, 0, 0,
0, 1, 1, 0, 1, 0, 0, 0, 0, 1,
1, 1, 1, 1, 0, 1, 0, 0, 1, 1,
1, 1, 0, 0, 1, 0, 1, 1, 1, 1,
1, 0, 0, 0, 0, 1, 0, 1, 1, 0,
0, 0, 0, 0, 0, 1, 1, 0, 1, 0,
0, 0, 0, 0, 1, 1, 1, 1, 0, 1,
0, 0, 0, 1, 1, 1, 0, 0, 1, 0};
int sum = 0;
bool func(int i)
{
if(i == 10)
{
sum++;
return 1;
}
for(int j = 0; j < 10; j++)
{
if(!record[j])
{
int tage = 0;
for(int n = 0; n < i; n++)
{
if(conflict[n][i] && ((j == thearray[n] - 1) || (j == thearray[n] + 1)))
tage++;
}
if(tage)
continue;
if(j == 10)
return 0;
thearray[i] = j;
record[j] = 1;
func(i + 1);
record[j] = 0;
}
}
return 0;
}
int main()
{
memset(thearray, -1, sizeof(thearray));
func(0);
cout << sum <<endl;
return 0;
}