2016 年蓝桥杯 c++ B 组 -----方格填数

题目链接

题目大意:

填数字,连续的两个数字不能相邻。
(左右、上下、对角都算相邻)一共有多少种可能的填数方案?

解题思路:

自己用 dfs 没写出来  

看题解  发现了一种有意思的写法  全排列  好机智噢

代码如下:

#include<iostream>
#include<algorithm>
using namespace std;
int a[10];
bool f(int x,int y)
{
	if(abs(a[y]-a[x])==1)
	  return false;
	else
	  return true;
}
int main()
{
	int i;
	for(i=0;i<10;i++)
	{
		a[i]=i;
	}
	int ans=0;
	do{
		if(f(0,1)&&f(0,3)&&f(0,4)&&f(0,5)&&f(1,2)&&f(1,4)&&f(1,5)&&f(1,6)&&f(2,5)&&f(2,6)&&f(3,4)&&f(3,7)&&f(3,8)&&f(4,5)&&f(4,7)&&f(4,8)&&f(4,9)&&f(5,6)&&f(5,8)&&f(5,9)&&f(6,9)&&f(7,8)&&f(8,9))
		    ans++;
		
	}while(next_permutation(a,a+10));
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43819762/article/details/108985229