-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.cpp
More file actions
73 lines (60 loc) · 991 Bytes
/
bfs.cpp
File metadata and controls
73 lines (60 loc) · 991 Bytes
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
72
73
///Implement Breadth-First Search in a graph
/// MADE BY CHETAN KHANNA
#include <bits/stdc++.h>
using namespace std;
vector<bool> visited;
vector<vector<int> >adj;
void add_edge(int x, int y)
{
adj[x].push_back(y);
}
void bfs(int s)
{
queue<int> q;
q.push(s);
visited[s] = true;
while (!q.empty()) {
int j = q.front();
q.pop();
cout << j << " ";
for (auto i = adj[j].begin(); i != adj[j].end(); i++) {
if (!visited[*i]) {
q.push(*i);
visited[*i] = true;
}
}
}
}
int main()
{
int n, e;
cin >> n >> e;
visited.assign(n, false);
adj.assign(n, vector<int>());
int a, b;
for (int i = 0; i < e; i++) {
cin >> a >> b;
add_edge(a, b);
}
for (int i = 0; i < n; i++) {
if (!visited[i])
bfs(i);
}
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
*/