2018 08 07,DFS入门中

搜索艰难入门,似乎走偏了。。。

看一道例题吧

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.

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.

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

分析:经典的深度优先搜索例题。题意也很简单,输入n,以1为起点,构建素数环,可用的元素为2到n。素数环,是相邻两数之和均为素数的环。

该怎么做呢,,,讲真,我看题解才把这道题目过掉,其实思路还是乱七八糟的。

基本思路,遍历所有可能的环,若能成功构成素数环,则输出;不能的话,回溯到上层,继续尝试。

最初的思路:从一开始,进行遍历,判断是否标记过以及是否符合素数环的要求,不能的就回溯。。。。然而我的代码只能实现输出一种素数环。嗯,现在想来,我的代码没有实现遍历每一个符合要求的环。

那么,思路没问题,问题在于如何码出来…………

ok,放上最后的代码,算是我默写的吧。惭愧不已

#include<stdio.h>
#include<math.h>
int idx[20],t0=0,num[21];
int n;
int is_prime(int p)
{
    int sqr=(int )sqrt(p);
    if(n==1) return 0;
    for(int i=2;i<=sqr;i++)
    {
        if(p%i==0 ) return 0;
    }
    return 1;
}
void dfs(int a)
{
    int i;
    if(a==n&&is_prime(num[a-1]+1))
    {
        for(i=0;i<a-1;i++)
            printf("%d ",num[i]);
        printf("%d\n",num[i]);
    }
    else
    {
        for(i=2;i<=n;i++)
        {
            if(idx[i]==0&&is_prime(num[a-1]+i))
           {
               idx[i]=1;
               num[a]=i;
               a++;
               dfs(a);
               idx[i]=0;
               a--;

           }

        }
    }

}

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0;i<20;i++)
        {
             idx[i]=0;
             num[i]=100;
        }

        num[0]=1;
        printf("Case %d:\n",++t0);
        dfs(1);
        printf("\n");
    }
}

猜你喜欢

转载自blog.csdn.net/zzuli_hanjk/article/details/81488658