Description
A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.
Note: the number of first circle should always be 1.

Note: the number of first circle should always be 1.

Input
n (0 < n < 20).
Output
The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in
lexicographical order.
You are to write a program that completes above process.
Print a blank line after each case.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input
6 8
Sample Output
Case 1: 1 4 3 2 5 6 1 6 5 2 3 4 Case 2: 1 2 3 8 5 6 7 4 1 2 5 8 3 4 7 6 1 4 7 6 5 8 3 2 1 6 7 4 3 8 5 2
解题思路
刚做了几道dsf&bfs的题,可能理解的还不到位,就写下自己的观点,有错误希望指出纠正。
dfs要注意的就是回溯的过程,回溯后还要还原used[]记录数组,继续深搜;
AC代码
#include<stdio.h>
#include<string.h>
#include<math.h>
int n,a[21],b[21];
bool used[21];
int func(int k)
{
for(int i=2; i<=sqrt(1.0*k); i++)
if(k%i == 0)
return 0;
return 1;
}
int dfs(int d, int w, int count) //d是当前数字, w是要入环数字,找第count个数字
{
if(func(d+w) == 0)
return 0;
else
b[count]=w;
if( count==n && func(w+1) )
{
for(int i=1; i<n; i++)
printf("%d ",b[i]);
printf("%d\n",b[n]);
return 1;
}
used[w] = 1;
for(int i=2; i<=n; i++)
if( used[i]==0 && dfs(w,i,count+1) ) //如果输出,最后一个dfs返回值为1,返回到上一层的for循环中,used[w]还原,再回溯再深搜
break;
used[w]=0; //一次for循环进行到底,找不到满足要求的下一个数,则used[w]还原,dfs返回值为0,回溯再深搜
return 0;
}
int main()
{
int cnt=1;
while( scanf("%d",&n)!=EOF )
{
for(int i=1; i<=n; i++)
a[i]=i;
b[1]=1;
memset(used,0,sizeof(used));
printf("Case %d:\n",cnt++);
if(n==1)
printf("1\n");
for(int i=2; i<=n; i++) //第一个数字是1,找第二个数字
dfs(1,i,2);
printf("\n");
}
return 0;
}