forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMessage Route.cpp
75 lines (66 loc) · 1.46 KB
/
Message Route.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Solution by: Pranav Nair
// Problem Link: https://cses.fi/problemset/task/1667
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
vector<vector<ll>> paths;
vector<bool> visited;
vector<ll> dist;
vector<ll> parent;
void bfs(ll s){
queue<ll> q;
q.push(s);
visited[s] = true;
dist[s] = 0;
parent[s] = 0;
while(!q.empty()){
ll curr = q.front();
q.pop();
for(ll computer : paths[curr]){
if(!visited[computer]){
q.push(computer);
visited[computer] = true;
dist[computer] = dist[curr] + 1;
parent[computer] = curr;
}
}
}
}
int main(){
ll n=0;
ll m=0;
cin>>n>>m;
for(ll i=0; i<=n; i++){
vector<ll> temp;
paths.push_back(temp);
visited.push_back(false);
dist.push_back(-1);
parent.push_back(-1);
}
for(ll i=0; i<m; i++){
ll a=0;
ll b=0;
cin>>a>>b;
paths[a].push_back(b);
paths[b].push_back(a);
}
bfs(1);
if(dist[n] == -1){
cout<<"IMPOSSIBLE";
return 0;
}
else{
vector<ll> route;
ll curr = n;
while(curr != 0){
route.push_back(curr);
curr = parent[curr];
}
reverse(route.begin(), route.end());
cout<<dist[n]+1<<"\n";
for(ll computer : route){
cout<<computer<<" ";
}
}
return 0;
}