Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1e5 + 3;
- int n, m;
- int used[N], dist[N], par[N];
- vector <int> g[N];
- int main(){
- cin >> n >> m;
- int start, finish;
- cin >> start >> finish;
- for (int i = 1; i <= m; i++) {
- int a, b;
- cin >> a >> b;
- g[a].push_back(b);
- g[b].push_back(a);
- }
- for (int i = 1; i <= n; i++) {
- dist[i] = -1;
- }
- queue <int> q;
- dist[start] = 0;
- used[start] = 1;
- q.push(start);
- while (!q.empty()) {
- int v = q.front();
- q.pop();
- for (int i = 0; i < g[v].size(); i++) {
- int to = g[v][i];
- if (!used[to]) {
- used[to] = 1;
- dist[to] = dist[v] + 1;
- par[to] = v;
- q.push(to);
- }
- }
- }
- if (dist[finish] == -1) {
- cout << -1 << endl;
- return 0;
- }
- cout << dist[finish] << endl;
- vector <int> path;
- int x = finish;
- while (x > 0) {
- path.push_back(x);
- x = par[x];
- }
- reverse(path.begin(), path.end());
- for (int x : path) {
- cout << x << " ";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement