今有7对数字:两个1,两个2,两个3,…两个7,把它们排成一行。
要求,两个1间有1个其它数字,两个2间有2个其它数字,以此类推,两个7之间有7个其它数字。如下就是一个符合要求的排列:
17126425374635
当然,如果把它倒过来,也是符合要求的。
请你找出另一种符合要求的排列法,并且这个排列法是以74开头的。
注意:只填写这个14位的整数,不能填写任何多余的内容,比如说明注释等。
一共14个数字,使用数组,按照规则每次填入两个相同的数,当7种(14个)数字全部填入后输出,
解题方法:dfs.
初始数组:74000040700000
可能需要4,5秒的时间,填空题不用管
#include <iostream>
using namespace std;
int map[15];//初始数组
bool vis[15];//第i个位置是否填过了
bool dir[8];//数字i是否用过了
bool f;//是否找到了
void dfs (int n,int t)
{
if (f)
{
return ;
}
if (n>14)
{
return;
}
if (t==7)
{
for (int i=1;i<=14;i++)
{
cout<<map[i];
}
cout<<endl;
f=true;
return;
}
if (vis[n])
{
dfs (n+1,t);
return ;
}
for (int i=1;i<=7;i++)
{
if (!dir[i]&&!vis[n+i+1]&&n+i+1<=14)
{
dir[i]=true;
vis[n]=vis[n+i+1]=true;
map[n]=map[n+i+1]=i;
dfs (n+1,t+1);
dir[i]=false;
vis[n]=vis[n+i+1]=false;
}
}
}
int main()
{
map[1]=map[1+7+1]=7;
map[2]=map[2+4+1]=4;
vis[1]=vis[2]=true;
vis[1+7+1]=true;
vis[2+4+1]=true;
dir[7]=dir[4]=true;
dfs(2,2);
return 0;
}