BFS

public
yeskendir.sultanov Apr 06, 2024 Never 46
Clone
C++ a.cpp 46 lines (39 loc) | 804 Bytes
1
#include <bits/stdc++.h>
2
#define ll long long
3
4
using namespace std;
5
6
int main() {
7
int n, m;
8
cin >> n >> m;
9
vector<int> g[n + 1];
10
for (int i = 0; i < m; ++i) {
11
int x, y;
12
cin >> x >> y;
13
g[x].push_back(y);
14
g[y].push_back(x);
15
}
16
17
int s, f;
18
cin >> s >> f;
19
20
vector<bool> used(n + 1, false);
21
vector<int> d(n + 1, 0);
22
queue<int> q;
23
24
used[s] = true;
25
d[s] = 0;
26
q.push(s);
27
28
while (!q.empty()) {
29
int v = q.front();
30
q.pop();
31
for (int to: g[v]) {
32
if (!used[to]) {
33
used[to] = true;
34
d[to] = d[v] + 1;
35
q.push(to);
36
}
37
}
38
}
39
40
if (!used[f]) {
41
cout << -1;
42
} else {
43
cout << d[f];
44
}
45
return 0;
46
}
47