#include using namespace std; #define rep(i,n) for (int i = 0; i < (n); i++) template inline bool chmax(T &a, T b) {return ((a < b) ? (a = b, true) : (false));} template inline bool chmin(T &a, T b) {return ((a > b) ? (a = b, true) : (false));} typedef long long ll; typedef pair P; struct edge { ll to, cost; edge(ll to, ll cost): to(to), cost(cost) {} }; ll MAX_V = 200005, INF = 1001001001001001; vector> G(MAX_V); vector d(MAX_V,INF); void dijkstra(int s) { priority_queue,greater

> que; d[s] = 0; que.emplace(0, s); while(!que.empty()) { P p = que.top(); que.pop(); int v = p.second; if(d[v] < p.first) continue; rep(i,G[v].size()) { edge e = G[v][i]; if(d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; que.emplace(d[e.to], e.to); } } } } int main() { ll n, m; cin >> n >> m; vector u(m), v(m); rep(i,m) cin >> u[i] >> v[i]; rep(i,m) { G[u[i]].emplace_back(v[i],1); } ll sum1 = 0, sum2 = 0; dijkstra(1); sum1 += d[n-1]; sum2 += d[n]; rep(i,MAX_V) { d[i] = INF; } //cout << " " << sum1 << " " << sum2 << endl; dijkstra(n-1); sum1 += d[n]; sum2 += d[1]; rep(i,MAX_V) { d[i] = INF; } //cout << " " << sum1 << " " << sum2 << endl; dijkstra(n); sum1 += d[1]; sum2 += d[n-1]; ll ans = min(sum1, sum2); if(ans >= INF) ans = -1; cout << ans << endl; return 0; }