知识点:图的遍历,回溯
这个题其实就是图的遍历然后加上回溯,但是有点坑的是,我们在找路径之前,要先判断1是不是能到k点,否则会超时,这个要不是看提示,还真想不到,因为如果不用别的函数来判断是不是连通的话,用求解的dfs函数,是自带回溯的,如果找不到,那么会比较费时间,会把所有的路径都走一遍,总之做这种图论的题总是会有很多这种考虑不周到,最后导致错误的地方,
这里存图没用邻接矩阵,用的是董晓讲的链式邻接表,因为我们每个节点要从小到大遍历它连着的节点,所有搜索之前对每个点连着的点排序,如果是采用链式前向星的话,我想不到该怎么写程序,就没有使用那种存图方式,
还有一点需要注意的是,题目输出,一个空格就够了,不需要样例里面长度为3的空格
#include <bits/stdc++.h>
using namespace std;
const int N = 25;
int n, k, vis[N], cnt;
vector<int> h[N], chosen;
vector<pair<int, int>> e;
void add(int a, int b) {
e.push_back(make_pair(a, b));
h[a].push_back((int) e.size() - 1);
}
bool cmp(int a, int b) {
return e[a].second < e[b].second;
}
bool bfs() {
queue<int> q;
q.push(1);
int dist[N] = {};
dist[1] = 1;
while (!q.empty()) {
int now = q.front(); q.pop();
if (now == k) return true;
for (int i = 0; i < (int) h[now].size(); i++) {
int ind = h[now][i];
int y = e[ind].second;
if (dist[y]) continue;
q.push(y);
dist[y] = 1;
}
}
return false;
}
void dfs(int x) {
if (x == k) {
for (int i = 0; i < (int) chosen.size(); i++) {
cout << chosen[i] << (i < (int) chosen.size() - 1 ? " " : "\n");
}
cnt++;
return;
}
for (int i = 0; i < (int) h[x].size(); i++) {
int ind = h[x][i];
int y = e[ind].second;
if (vis[y]) continue;
vis[y] = 1;
chosen.push_back(y);
dfs(y);
chosen.pop_back();
vis[y] = 0;
}
}
int main() {
int tt = 1;
while (cin >> k) {
n = 0; cnt = 0;
e.clear();
for (int i = 0; i < N; i++) h[i].clear();
cout << "CASE " << tt++ << ":\n";
int a, b;
while (cin >> a >> b && a) {
add(a, b);
add(b, a);
n = max(n, max(a, b));
}
for (int i = 1; i <= n; i++) {
sort(h[i].begin(), h[i].end(), cmp);
}
if (bfs()) {
vis[1] = 1;
chosen.push_back(1);
dfs(1);
vis[1] = 0;
chosen.pop_back();
}
printf("There are %d routes from the firestation to streetcorner %d.\n", cnt, k);
}
return 0;
}