递归应用一:回溯法枚举解决素数环问题
#include<stdio.h>
int ans[17];
bool mark[17];
int prime[11] = { 2,3,5,7,11,13,17,19,23,29,31 };
bool judge(int x)
{
for (int i = 0; i < 11; i++)
if (x == prime[i])
return true;
return false;
}
void DFS(int num,int n)
{
if (num > 1)
if (judge(ans[num] + ans[num - 1]) == false)
return;
if (num == n)
{
if (judge(ans[n] + ans[1]) == false)
return;
for (int i = 1; i <= n; i++)
printf("%d ", ans[i]);
printf("\n");
return;
}
for (int i = 2; i <= n; i++)
{
if (mark[i] == false)
{
mark[i] = true;
ans[num + 1] = i;
DFS(num + 1, n);
mark[i] = false;
}
}
}
int main()
{
int n, cas = 0;
while (scanf("%d", &n) != EOF)
{
for (int i = 0; i < 17; i++)
mark[i] = false;
cas++;
printf("Case %d:\n", cas);
ans[1] = 1;
DFS(1, n);
}
return 0;
}