#include #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") using namespace std; const int inf = 100000000; vector bfs(int s, int N, vector> &G) { vector dist(N, inf); dist[s] = 0; queue que; que.push(s); while(!que.empty()) { int u = que.front(); que.pop(); for(int v : G[u]) { if(dist[v] == inf) { dist[v] = dist[u] + 1; que.push(v); } } } return dist; } int main() { cin.tie(0); cout.tie(0); ios::sync_with_stdio(false); int N, M; cin >> N >> M; vector> G(N); while(M--) { int u, v; cin >> u >> v; G[--u].emplace_back(--v); } vector d0 = bfs(0, N, G); vector d1 = bfs(N - 2, N, G); vector d2 = bfs(N - 1, N, G); int ans = min(d0[N - 2] + d1[N - 1] + d2[0], d0[N - 1] + d2[N - 2] + d1[0]); cout << (ans >= inf ? -1 : ans) << '\n'; return 0; }