-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathbfs.cpp
More file actions
40 lines (32 loc) · 714 Bytes
/
bfs.cpp
File metadata and controls
40 lines (32 loc) · 714 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
#include <bits/stdc++.h>
using namespace std;
void bfs(vector<int> v[], int n, int root) {
bool visited[n];
for(int i = 0; i < n; i++)
visited[i] = false;
queue<int> q;
visited[root] = true;
q.push(root);
while(!q.empty()) {
int i = q.front();
q.pop();
cout << i << " ";
for(int j = 0; j < v[i].size(); j++)
if(!visited[v[i][j]]) {
visited[v[i][j]] = true;
q.push(v[i][j]);
}
}
}
int main(int argc, char const *argv[]) {
int n, e;
cin >> n >> e;
vector<int> v[n];
for(int i = 0; i < e; i++) {
int x, y;
cin >> x >> y;
v[x - 1].push_back(y - 1);
}
bfs(v, n, 0);
return 0;
}