题解:P1811 最短路
题目分析
没想到什么好思路,随便胡了个迭代加深搜索上去。
IDDFS 具体过程(代码角度):
初始化一个变量
在 dfs 函数里,先判断当前深度
接着遍历当前节点
如果在某次循环中 dfs 找到了终点
当最终找到最短路径后,输出
代码
#include <bits/stdc++.h>
using namespace std;
int n, m, k, p[3005][3005], dep, vis[3005][3005], ans = 0x3f3f3f3f;
int path[30005], ans2[30005];
vector <int> edge[30005];
inline void dfs (int x, int fa, int d) {
if (d > dep) return;
if (x == n) {
if (ans > d) {
ans = d;
memcpy (ans2, path, sizeof (path));
}
return ;
}
for (auto y : edge[x]) {
if (vis[x][y] || p[fa][x] == y) continue;
vis[x][y] = 1;
path[d] = y;
dfs (y, x, d + 1);
path[d] = 0;
vis[x][y] = 0;
}
}
int main () {
scanf ("%d%d%d", &n, &m, &k);
for (int i = 1; i <= m; i++) {
int a, b;
scanf ("%d%d", &a, &b);
edge[a].push_back (b);
edge[b].push_back (a);
}
for (int i = 1; i <= k; i++) {
int x, y, z;
scanf ("%d%d%d", &x, &y, &z);
p[x][y] = z;
}
while (-1) {
vis[0][1] = 1;
path[0] = 1;
dfs (1, 0, 1);
if (ans != 0x3f3f3f3f) break;
dep++;
}
printf ("%d\n", ans - 1);
for (int i = 0; i <= ans - 1; i++) printf ("%d ", ans2[i]);
return 0;
}