-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.cpp
60 lines (48 loc) · 1.32 KB
/
bfs.cpp
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
#include <bits/stdc++.h>
#define ll long long
#define mx 10000
using namespace std;
/***************************************************************************************/
vector<int > graph[mx];
void bfs(bool vis[], int dis[], int source) {
queue<int >q;
int cont = 0;
vis[source] = 1;
dis[source] = 0;
q.push(source);
while (!q.empty()) {
int node = q.front();
q.pop();
for (int i = 0; i < graph[node].size(); i++) {
int next = graph[node][i];
if (!vis[next]) {
q.push(next);
vis[next] = 1;
dis[next] = dis[node] + 1;
}
}
}
}
void solve() {
int edge;
cin >> edge;
if (edge == 0) {
cout << "No answer" << endl;
}
else {
for (int i = 0; i < edge; i++) {
int x, y;
cin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
bool vis[mx] = {false};
int dis[mx];
int source;
cin >> source ;
bfs(vis, dis, source);
}
}
int main() {
solve();
}