总体思路很简单,回溯,但直接用矩阵回溯会TLE。因为可能在1与目标点之间不存在通路(即:1 与 目标点分别存在于两个隔绝的联通图中),这样如果直接从1开始往下回溯,会无谓检查到许多无用的点浪费时间,我们可以先将所有与目标点联通的点存于一个数组中,仅在这个数组中查找,就省去很多无谓的查找时间。
代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
int cct, fcount, num, _max, save[21], a[21];
bool vis[21][21], v[21], vv[21];
void dfs_1(int cur)//将所有与目标点联通的点存入一个点集合里
{
vv[cur] = true;
a[_max++] = cur;
for (int i = 1; i < 21; i++)
if (!vv[i] && vis[cur][i])
dfs_1(i);
}
void dfs_2(int cur, int node)
{
if(node == num)
{
++fcount;
printf("1");
for(int i = 0; i < cur; i++)
printf(" %d", save[i]);
puts("");
}
for(int i = 0; i < _max; i++)
if(!v[a[i]] && vis[node][a[i]])
{
save[cur] = a[i];
v[a[i]] = true;
dfs_2(cur + 1, a[i]);
v[a[i]] = false;
}
}
int main()
{
#ifdef test
freopen("sample.txt", "r", stdin);
#endif
int x, y, fct = 0;
memset(v, false, sizeof(v));
while(scanf("%d", &num) != EOF)
{
_max = fcount = cct = 0;
memset(vv, false, sizeof(vv));
memset(vis, false, sizeof(vis));
while(1)
{
scanf("%d%d", &x, &y);
if(!x || !y)
break;
vis[x][y] = vis[y][x] = true;
}
dfs_1(num);
sort(a, a + _max);
v[1] = true;
printf("CASE %d:\n", ++fct);
dfs_2(0, 1);
printf("There are %d routes from the firestation to streetcorner %d.\n", fcount, num);
}
return 0;
}