Prime Ring Problem

 1 #include<stdio.h>
 2 #include<string.h>
 3 
 4 int prime[38]={0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1};
 5 int visit[21],result[21];
 6 int n;
 7 
 8 int dfs(int num)
 9 {
10     int print(int m);
11     int i;
12     if(num==n && prime[result[num]+result[1]])
13         print(num);
14     else
15     {
16         for(i=2;i<=n;i++)
17         {
18             if(prime[result[num]+i] && !visit[i])
19             {
20                 result[num+1]=i;
21                 visit[i]=1;
22                 dfs(num+1);
23                 visit[i]=0;
24             }
25         }
26     }
27     return 0;
28 }
29 
30 int print(int m)
31 {
32     int i;
33     printf("%d",result[1]);
34     for(i=2;i<=m;i++)
35         printf(" %d",result[i]);
36     printf("\n");
37     return 0;
38 }
39 
40 int main()
41 {
42     int i=1;
43     while(scanf("%d",&n)==1)
44     {
45         printf("Case %d:\n",i++);
46         memset(visit,0,sizeof(visit));
47         visit[1]=1;
48         result[1]=1;
49         dfs(1);
50         printf("\n");
51     }
52     return 0;
53 }

//主要是利用深搜算,重点在深搜部分,result[num+1]=i; visit[i]=1;  dfs(num+1);  visit[i]=0;这几句很重要,result[num+1]不能写成result[++num]
//因为当回溯时,num的值不能变。

posted @ 2012-06-21 23:53  Robot_Asia  阅读(730)  评论(0编辑  收藏  举报