題意
題目鏈接: 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++);
}
}