-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbfs.cpp
More file actions
52 lines (49 loc) · 1.07 KB
/
bfs.cpp
File metadata and controls
52 lines (49 loc) · 1.07 KB
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
#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
#define MAXN 100000
using namespace std;
queue <int> q, ans;
bool used[MAXN];
int main() {
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
int n, m, s;
cin >> n >> m >> s;
vector<vector<int>> g (n);
for (int i = 0; i < m; ++i){
int a, b;
cin >> a >> b;
--a; --b;
g[a].push_back(b);
g[b].push_back(a);
}
--s;
q.push(s);
used[s] = true;
ans.push(s+1);
while (!q.empty()){
int v = q.front();
q.pop();
for (int i = 0; i < g[v].size(); ++i) {
int destination = g[v][i];
if (!used[destination]) {
used[destination] = true;
q.push(destination);
ans.push(destination+1);
}
}
}
if (ans.size() == n){
for (int i = 0; i < n; ++i){
cout << ans.front() << ' ';
ans.pop();
}
} else{
cout << -1;
}
fclose(stdin);
fclose(stdout);
return 0;
}