题意:给出一个目标节点,和各个节点的连通情况,然后寻找从1到这个目标节点的所有可能路径。
题解:直接回溯会TLE。。。所以需要剪枝,可以将所有能到达目标节点的节点放在一起再排个序,保证了图的连通性,这样就不会在某个点死循环了。
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 22;
int g[N][N], ans, res[N], vis[N], n, num, node[N], tar;
void init() {
memset(g, 0, sizeof(g));
memset(res, 0, sizeof(res));
memset(vis, 0, sizeof(vis));
ans = num = n = 0;
}
void search(int cur) {
node[num++] = cur;
vis[cur] = 1;
for (int i = 1; i <= n; i++)
if (g[cur][i] && !vis[i]) {
search(i);
}
}
void dfs(int cur, int count) {
if (cur == tar) {
printf("%d", res[0]);
for (int i = 1; i < count; i++)
printf(" %d", res[i]);
printf("\n");
ans++;
return;
}
for (int i = 0; i < num; i++)
if (g[cur][node[i]] && !vis[node[i]]) {
vis[node[i]] = 1;
res[count] = node[i];
dfs(node[i], count + 1);
vis[node[i]] = 0;
}
}
int main() {
int a, b;
int t = 1;
while (scanf("%d", &tar) != EOF) {
init();
while (scanf("%d%d", &a, &b) && a) {
if (a > n)
n = a;
if (b > n)
n = b;
g[a][b] = g[b][a] = 1;
}
printf("CASE %d:\n", t++);
search(tar);
sort(node, node + num);
memset(vis, 0, sizeof(vis));
vis[1] = 1;
res[0] = 1;
dfs(1, 1);
printf("There are %d routes from the firestation to streetcorner %d.\n", ans, tar);
}
return 0;
}