BFS输出遍历顺序(邻接链表)
作者:
nxdxml
,
2020-12-06 22:22:39
,
所有人可见
,
阅读 538
#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
int path[N], h[N], e[N], ne[N], n, m;
int idx;
int q[N];
bool st[N];
int cnt;
void add(int a, int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++ ;
}
void bfs(){
int hh = 0, tt = 0;
q[0] = 1;
while(hh <= tt){
int t = q[hh ++ ];
if(!st[t]) path[cnt ++ ] = t, st[t] = 1;
for(int i = h[t]; i != -1; i = ne[i]){
int j = e[i];
if(!st[j]){
q[ ++ tt] = j;
}
}
}
}
int main(){
memset(h, -1, sizeof h);
cin >> n >> m;
while(m -- ){
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
}
bfs();
for(int i = 0; i < cnt; i ++ ) printf("%d ", path[i]);
return 0;
}
/*
9 22
1 4
1 3
1 2
2 6
2 5
2 1
3 8
3 7
3 1
4 1
5 9
5 2
6 9
6 2
7 9
7 3
8 9
8 3
9 8
9 7
9 6
9 5
*/