题目大意:给出一张图,求从 1 到 n 的所有路径。
解题思路:回溯 + 剪枝。map[][] 存图,arv[i][j]表示 i 点是否能够到达 j 点,这就是剪枝条件,对于每个点要判断是否能够到达 n 点,如果不能到就不要再查找了否则会 TLE。然后就是回溯。arv 忘记初始化 TLE 了好几次。。。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
bool map[50][50], arv[50][50], vis[50];
int as[50];
int n, m, ans, cnt = 0;
void dfs(int now, int cnt) {
if (now == n) {
for (int i = 0; i < cnt-1; i++)
printf("%d ", as[i]);
printf("%d\n", as[cnt-1]);
ans++;
return;
}
for (int i = 1; i <= m; i++)
if (!vis[i] && map[now][i] && arv[i][n]) {
vis[i] = true;
as[cnt] = i;
dfs(i, cnt+1);
vis[i] = false;
}
}
int main() {
while (scanf("%d", &n) != EOF) {
memset(map, 0, sizeof(map));
memset(arv, 0, sizeof(arv));
int a, b;
m = 0;
while (scanf("%d%d", &a, &b) && a+b) {
map[a][b] = map[b][a] = true;
arv[a][b] = arv[b][a] = true;
if (a > m) m = a;
if (b > m) m = b;
}
for (int k = 1; k <= m; k++)
for (int i = 1; i <= m; i++)
for (int j = 1; j <= m; j++)
if (arv[i][k] && arv[k][j])
arv[i][j] = true;
printf("CASE %d:\n", ++cnt);
ans = 0;
as[0] = 1;
vis[1] = true;
dfs(1, 1);
printf("There are %d routes from the firestation to streetcorner %d.\n", ans, n);
}
return 0;
}