#include using namespace std; typedef long long ll; constexpr int Inf = 2000000030; constexpr ll INF= 2000000000000000001; constexpr ll MOD = 1000000007; const double PI = 3.14159265358979323846; typedef pair P; typedef pair PP; template vector make_vector(size_t s) { return vector(s); } template auto make_vector(size_t s,Args... args) { return vector(s,make_vector(args...)); } template inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } ll mod(ll val, ll M) { val = val % M; if(val < 0) { val += M; } return val; } template T modpow(T N, T P, T M){ if(P == 0) return 1; if(P < 0) return 0; if(P % 2 == 0){ ll t = RS(N, P/2, M); if(M == -1) return t * t; return t * t % M; } if(M == -1) return N * modpow(N,P - 1,M); return N * modpow(N, P-1, M) % M; } struct edge{ int to; ll cost; }; int N; //頂点数 vector graph[200010]; ll dist[200010]; //頂点sからの最短距離 int pre[200010]; void Dijkstra(int s) { //greater

を指定することでfirstが小さい順に取り出せる priority_queue,greater

> que; fill(dist,dist + N,INF); fill(pre,pre + N,-1); dist[s] = 0; que.push(P(0,s)); while(!que.empty()) { P p = que.top(); que.pop(); int v = p.second; if(dist[v] < p.first) { continue; } for(auto x:graph[v]) { if(chmin(dist[x.to],dist[v] + x.cost)) { pre[x.to] = v; que.push(P(dist[x.to],x.to)); } } } } //最短路を取得 vector get_path(int t) { vector path; while(t != -1) { path.push_back(t); t = pre[t]; } reverse(path.begin(),path.end()); return path; } int main() { cin >> N; int M; cin >> M; for(int i = 0;i < M;i++) { int a,b; cin >> a >> b; a--; b--; graph[a].push_back(edge{b,1}); graph[b].push_back(edge{a,1}); } Dijkstra(0); if(dist[N - 1] == INF) cout << -1 << endl; else cout << dist[N - 1] << endl; }