TOJ 1529. Granny's Bike--哈密顿回路

题意

题目链接: 1529. Granny’s Bike
题意不难理解,就是给一个图,问能否从出发点经历所有点回到出发点。
SampleInput
5
0 2 5
0 1 3
2 4
0 3 5
1 4
4
0 2 3 4
1 3
1 2
0 1
0

SampleOutput
Case 1: Granny can make the circuit.
Case 2: Granny can not make the circuit.

这里需要说明的是输入问题,多个样例,第一个表示有5个地点(不包括起点 0), 序号为1-5 ,然后接下来有 5 行,每一行的若干数字都表示与当前行有边相连。
这里由于不确定有多少条边数,因此输入的时候需要注意, 可以以字符串输入,然后再解析为 数字。

思路

就是哈密顿回路的问题, 不过数据量很小,只有10 直接dfs 搜索即可;

代码

#include <stdio.h>
#include <string.h>
using namespace std;

int m[15][15],used[15],n;

bool dfs(int k,int step)
{
    if(k==0&&step==n+1) return true;
    for(int i=0; i<=n;i++)
    {
        if(!used[i]&&m[k][i])
        {
            used[i]=1;
            if(dfs(i,step+1)) return true;
            else used[i]=0;
        }
    }
    return false;
}
int main()
{
    int t=1;
    while(scanf("%d",&n)&&n)
    {
        memset(m,0,sizeof(m));
        memset(used,0,sizeof(used));
        getchar();
        for(int i=1; i<=n;i++)
        {
            char ch[30];
            int j;

            gets(ch);
            for(j=0;j<strlen(ch);j++)
                if(ch[j]==' ')
                {
                    m[i][ch[j-1]-'0']=m[ch[j-1]-'0'][i]=1;
                }
            m[i][ch[j-1]-'0']=m[ch[j-1]-'0'][i]=1;
        }
        if(dfs(0,0)) printf("Case %d: Granny can make the circuit.\n",t++);
        else printf("Case %d: Granny can not make the circuit.\n",t++);
    }
}

你可能感兴趣的:(DFS)