//#define _GLIBCXX_DEBUG #include #include #include #include using namespace std; using namespace atcoder; using ll = long long; using mint = modint998244353; const double pi = 3.14159265359879323846264338327950288419; const ll INF = 9 * 1e6; using p = pair; int main() { int n, m; cin >> n >> m; map> mp; for(int i = 0; i < m; i++){ int U, V; cin >> U >> V; mp[U-1].push_back(V-1); } vector dis_from_0(n, INF); dis_from_0[0] = 0; queue q; q.push(0); while(!q.empty()){ int v = q.front(); q.pop(); for(auto nv : mp[v]){ if(dis_from_0[nv] != INF) continue; dis_from_0[nv] = dis_from_0[v] + 1; q.push(nv); } } vector dis_from_n(n, INF); dis_from_n[n-1] = 0; q.push(n-1); while(!q.empty()){ int v = q.front(); q.pop(); for(auto nv : mp[v]){ if(dis_from_n[nv] != INF) continue; dis_from_n[nv] = dis_from_n[v] + 1; q.push(nv); } } vector dis_from_n1(n, INF); dis_from_n1[n-2] = 0; q.push(n-2); while(!q.empty()){ int v = q.front(); q.pop(); for(auto nv : mp[v]){ if(dis_from_n1[nv] != INF) continue; dis_from_n1[nv] = dis_from_n1[v] + 1; q.push(nv); } } //for(auto c : dis_from_n1) cerr << c << " "; ll zero_n_n1 = dis_from_0[n-1] + dis_from_n[n-2] + dis_from_n1[0], zero_n1_n = dis_from_0[n-2] + dis_from_n1[n-1] + dis_from_n[0]; cout << (min(zero_n_n1, zero_n1_n) >= INF ? -1:min(zero_n_n1, zero_n1_n)) << endl; }