-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cpp
More file actions
67 lines (54 loc) · 1 KB
/
BFS.cpp
File metadata and controls
67 lines (54 loc) · 1 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <cstdio>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
signed n, m ,s;
vector<signed> *vertex = NULL;
bool visited[100001];
queue<signed> q, solution;
int main(){
ifstream In("input.txt");
ofstream Out("output.txt");
In >> n;
In >> m;
In >> s;
vertex = new vector<signed>[n+1];
if(n == 0){
Out << -1;
Out.close();
return 0;
}
for(signed i = 0; i < m; i++){
signed v1, v2;
In >> v1;
In >> v2;
vertex[v1].push_back(v2);
vertex[v2].push_back(v1);
}
q.push(s);
solution.push(s);
visited[s] = true;
while(!q.empty()){
signed v = q.front();
q.pop();
for(signed i = 0; i < vertex[v].size(); i++)
if(!visited[vertex[v][i]]){
q.push(vertex[v][i]);
visited[vertex[v][i]] = true;
solution.push(vertex[v][i]);
}
}
for(signed i = 1; i <= n; i++)
if(!visited[i]){
Out << -1;
Out.close();
return 0;
}
while(!solution.empty()){
Out << solution.front() << ' ';
solution.pop();
}
Out.close();
}