File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments