如图,如下的10个格子,填入0~9的数字。要求:连续的两个数字不能相邻。 (左右、上下、对角都算相邻)一共有多少种可能的填数方案?
请填写表示方案数目的整数。
思路:
从左到右从上到下标为0~9
将a[10]中的数字依次填入
只要将a数组从0123456789一直全排列试到9876543210
测试每一个结果是否满足,满足条件的次数累加得到的就是方案数目
#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
int a[10]= {0,1,2,3,4,5,6,7,8,9};
//判断相邻数字是否连续
int judge(int i, int j)
{
if(abs(a[i]-a[j])==1) return 1;
return 0;
}
bool check()
{
if (judge(0, 1) || judge(0, 3) ||judge(0, 4) ||judge(0, 5) ||judge(1, 2)||judge(1, 4) ||judge(1, 5) ||judge(1,6) ||judge(2, 5) ||judge(2, 6) ||judge(3, 4) ||judge(3, 7) ||judge(3, 8) || judge(4, 5) ||judge(4, 7) || judge(4, 8) ||judge(4, 9) ||judge(5, 6) ||judge(5, 8) || judge(5, 9) || judge(6, 9)|| judge(7, 8) ||judge(8, 9))
return false;
return true;
}
int main()
{
int ans = 0;
do
{
if(check())
{
ans++;
}
}
while(next_permutation(a,a+10));
printf("%d\n",ans);
}