题目链接:哈密顿绕行世界问题(HDU 2181)
思路
起点和终点相同的dfs
代码
#include <stdio.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
#include <queue>
#include <string.h>
#include <set>
#include <stack>
#include <stdlib.h>
#include <time.h>
using namespace std;
bool v[21][21];//保存结点连通情况
bool f[21];//记录已经过的结点
int p[21];//记录路径
int num;
void dfs(int m, int x, int k)
{
p[k] = x;
if(k == 20)
{
if(x == m)
{
cout<<num++<<": ";
for(int i=0;i<=20;++i)
cout<<" "<<p[i];
cout<<endl;
}
return;
}
for(int i=1;i<=20;++i)
{
if(!f[i] && v[i][x])
{
f[i] = 1;
dfs(m, i, k+1);
f[i] = 0;
}
}
}
int main()
{
int a,b,c;
while(1)
{
memset(f, 0, sizeof(f));
memset(v, 0, sizeof(v));
num = 1;
cin>>a;
if(a == 0)
break;
cin>>b>>c;
v[1][a] = v[1][b] = v[1][c] = 1;
for(int i=2;i<=20;++i)
{
cin>>a>>b>>c;
v[i][a] = v[i][b] = v[i][c] = 1;
}
int m;
cin>>m;
dfs(m, m, 0);
}
return 0;
}