Skip to content

Commit 3c88515

Browse files
Merge pull request ABHISHEK-AMRUTE#98 from ankitcdry1612/master
Hacktoberfest
2 parents 018804b + 58636d6 commit 3c88515

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

C++/BFS.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include <bits/stdc++.h>
2+
#define pb push_back
3+
4+
using namespace std;
5+
6+
vector<bool> v;
7+
vector<vector<int> > g;
8+
9+
void edge(int a, int b)
10+
{
11+
g[a].pb(b);
12+
13+
// for undirected graph add this line
14+
// g[b].pb(a);
15+
}
16+
17+
void bfs(int u)
18+
{
19+
queue<int> q;
20+
21+
q.push(u);
22+
v[u] = true;
23+
24+
while (!q.empty()) {
25+
26+
int f = q.front();
27+
q.pop();
28+
29+
cout << f << " ";
30+
31+
// Enqueue all adjacent of f and mark them visited
32+
for (auto i = g[f].begin(); i != g[f].end(); i++) {
33+
if (!v[*i]) {
34+
q.push(*i);
35+
v[*i] = true;
36+
}
37+
}
38+
}
39+
}
40+
41+
// Driver code
42+
int main()
43+
{
44+
int n, e;
45+
cin >> n >> e;
46+
47+
v.assign(n, false);
48+
g.assign(n, vector<int>());
49+
50+
int a, b;
51+
for (int i = 0; i < e; i++) {
52+
cin >> a >> b;
53+
edge(a, b);
54+
}
55+
56+
for (int i = 0; i < n; i++) {
57+
if (!v[i])
58+
bfs(i);
59+
}
60+
61+
return 0;
62+
}

0 commit comments

Comments
 (0)