#include using namespace std; #define ll long long const ll INF = 1LL << 60; vector bfs(int start, vector> &graph, int N) { vector dists(N, INF); dists[start] = 0; queue> q; q.push(pair(start, 0)); while (!q.empty()) { int now_v = q.front().first; ll d = q.front().second; q.pop(); for (int next_v : graph[now_v]) { if (dists[next_v] < INF) continue; dists[next_v] = d + 1; q.push(pair(next_v, d + 1)); } } return dists; } int main() { int N, M; cin >> N >> M; vector> graph(N, vector()); for (int i = 0; i < M; i++) { int u, v; cin >> u >> v; u -= 1, v -= 1; graph[u].push_back(v); } vector dist_0 = bfs(0, graph, N); vector dist_N_2 = bfs(N-2, graph, N); vector dist_N_1 = bfs(N-1, graph, N); // 町1 -> 町N-1 -> 町N -> 町1 の最短経路の長さ ll d_1 = dist_0[N-2] + dist_N_2[N-1] + dist_N_1[0]; // 町1 -> 町N -> 町n-1 -> 町1 の最短経路の長さ ll d_2 = dist_0[N-1] + dist_N_1[N-2] + dist_N_2[0]; ll ans = min(d_1, d_2); if (ans < INF) cout << ans << endl; else cout << -1 << endl; }