#include #include using namespace std; using namespace atcoder; using ll = long long; using ld = long double; using mint = modint998244353; const ll INF = 1LL << 60; vector bfs(int start, vector> &graph, int N) { vector dists(N, INF); dists[start] = 0; queue> q; q.push({start, 0}); while (!q.empty()) { auto [u, d] = q.front(); q.pop(); for (int v: graph[u]) { if (dists[v] < INF) continue; dists[v] = d + 1; q.push({v, dists[v]}); } } return dists; } int main() { int N, M; cin >> N >> M; vector> graph(N); for (int i = 0; i < M; i++) { int u, v; cin >> u >> v; u--, v--; graph[u].push_back(v); } vector dists_0 = bfs(0, graph, N); vector dists_N_2 = bfs(N - 2, graph, N); vector dists_N_1 = bfs(N - 1, graph, N); ll ans1 = dists_0[N - 2] + dists_N_2[N - 1] + dists_N_1[0]; ll ans2 = dists_0[N - 1] + dists_N_1[N - 2] + dists_N_2[0]; ll ans = min(ans1, ans2); cout << (ans >= INF ? -1: ans) << endl; return 0; }