-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS.cpp
71 lines (62 loc) · 1017 Bytes
/
BFS.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
implementation of BFS
@author Amirul islam
_
_|_ o._ o._ __|_| _. _|_
_>| ||| ||| |(_|| |(_|_>| |
_|
*/
#include <bits/stdc++.h>
using namespace std;
const int mx = 1e5;
bool vis[mx];
vector <int> graph[mx];
void bfs(int u) {
queue <int> q;
q.push(u);
vis[u] = true;
while (!q.empty()) {
u = q.front();
q.pop();
cout << u << " ";
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i];
if (!vis[v]) {
q.push(v);
vis[v] = true;
}
}
}
}
int main() {
freopen("in", "r", stdin);
int node, edge, u, v;
cin >> node >> edge;
while (edge--) {
cin >> u >> v;
graph[u].push_back(v);
}
for (int i = 0; i < node; i++) {
if (!vis[i]) {
bfs(i);
}
}
cout << "\n";
return 0;
}
/*
Input:
8 10
0 1
0 2
0 3
0 4
1 5
2 5
3 6
4 6
5 7
6 7
Output:
0 1 2 3 4 5 6 7
*/