#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
const int maxn = 1e4 + 50;
const int INF = 0x3f3f3f3f;
int head[maxn], cnt = 0;
int n, m;
int vis[maxn];
struct Edge {
int to, next, w;
}edge[maxn << 1];
void add(int u, int v, int w) {
edge[cnt].to = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt++;
}
void init() {
for (int i = 0; i < m; ++i) {
head[i] = -1;
}
}
void dfs(int st) {
if (st >= n)return;
if (!vis[st]) {
printf("V%d ", st);
vis[st] = 1;
}
for (int i = head[st]; i != -1; i = edge[i].next) {
if (!vis[edge[i].to])
dfs(edge[i].to);
}
}
int que[maxn];
int pos = 0, p = 0;
void bfs(int st) {
que[pos++] = st;
while (p != pos) {
int temp = que[p];
p++;
if (vis[temp])continue;
vis[temp] = 1;
printf("V%d ", temp);
for (int i = head[temp]; i != -1; i = edge[i].next) {
if (vis[edge[i].to])continue;
que[pos++] = edge[i].to;
}
}
}
int main() {
scanf("%d%d", &n, &m);
init();
for (int i = 0; i < m; ++i) {
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
}
int st;
while (~scanf("%d", &st)) {
if (st == -1)break;
memset(vis, 0, sizeof vis);
if (st < n)
printf("BFS From V%d:", st);
bfs(st);
puts("");
memset(vis, 0, sizeof vis);
if (st < n)
printf("DFS From V%d:", st);
dfs(st);
puts("");
}
return 0;
}
数据结构之图的遍历(bfs,dfs)
最新推荐文章于 2024-07-15 17:29:31 发布