#include #define rep(i,n) for(int i = 0; i < (n); i++) using namespace std; typedef long long ll; // g <- pair < v , cost > template < class T > vector< T > dijkstra(vector>> &graph, int s) { T INF = numeric_limits< T >::max(); vector dist(graph.size(), INF); priority_queue, vector>, greater>> q; q.push({dist[s] = T(0), s}); while(!q.empty()){ auto [uc, ui] = q.top(); q.pop(); if(uc != dist[ui]) continue; for(auto [vi, vc] : graph[ui]) if(dist[vi] > uc + vc) q.push({dist[vi] = uc + vc, vi}); } return dist; } int main(){ cin.tie(0); ios::sync_with_stdio(0); int N,M; cin >> N >> M; vector>> G(N); rep(i,M) { int a,b; cin >> a >> b; a--; b--; G[a].push_back({b, 1}); G[b].push_back({a, 1}); } int ans = dijkstra(G, 0)[N - 1]; cout << (ans < int(1e9) ? ans : -1) << endl; }