# 递归（dfs深度优先搜索）

$\bg_white&space;\begin{cases}&space;F(n)&space;=&space;G(n,F(n-1))&space;&&space;\text{&space;}&space;n>0&space;\\&space;F(n)&space;=&space;a&space;&&space;\text{&space;}&space;n&space;=&space;0&space;\end{cases}$

bool vis[20];
int ans = 0;
int a[20];

bool isprime(int x)
{

for(int i = 2;i <= sqrt(x);i++)
{

if(x % i == 0)
{

return false;
}
}
return true;
}

int main()
{

for(int i = 1;i <= 20;i++)
{

if(vis[i])
{

continue;
}
vis[i] = true;
a[1] = i;
for(int j = 1;j <= 20;j++)
{

if(vis[j])
{

continue;
}
if(!isprime(a[1] + j))
{

continue;
}
vis[j] = true;
a[2] = j;
for(int k = 1;k <= 20;k++)
{

if(vis[k])
{

continue;
}
if(!isprime(a[2] + k) || !isprime(a[1] + k))
{

continue;
}
ans++;
}
vis[j] = false;
}
vis[i] = false;
}
return 0;
}


1.排除非法情况
2.记录相关信息
3.下一层操作
4.消除vis


bool vis[20];
int ans = 0;
int a[20];
int n;

bool isprime(int x)
{

for(int i = 2;i <= sqrt(x);i++)
{

if(x % i == 0)
{

return false;
}
}
return true;
}

void dfs(int now)
{

if(now == n + 1)
{

if(isprime(a[n] + a[1]))
{

ans++;
}
return;
}
for(int i = 1;i <= 20;i++)
{

if(!vis[i])
{

if(now > 1 && !isprime(a[now - 1] + i))
{

continue;
}
vis[i] = true;
a[now] = i;
dfs(now + 1);//循环n次
vis[i] = false;
}
}
}