#include #include #include #include using namespace std; int main() { int n, m; cin >> n >> m; vector> G(n); for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; u--; v--; G[u].push_back(v); } queue test; vector dis1(n, -1), dis2(n, -1), dis3(n, -1); dis1[0] = 0; test.push(0); while(!test.empty()) { int p = test.front(); test.pop(); for (int w : G[p]) { if (dis1[w] != -1) continue; dis1[w] = dis1[p] + 1; test.push(w); } } dis2[n - 2] = 0; test.push(n - 2); while(!test.empty()) { int p = test.front(); test.pop(); for (int w : G[p]) { if (dis2[w] != -1) continue; dis2[w] = dis2[p] + 1; test.push(w); } } dis3[n - 1] = 0; test.push(n - 1); while(!test.empty()) { int p = test.front(); test.pop(); for (int w : G[p]) { if (dis3[w] != -1) continue; dis3[w] = dis3[p] + 1; test.push(w); } } int res = -1; if (dis1[n - 2] != -1 && dis2[n - 1] != -1 && dis3[0] != -1) res = dis1[n - 2] + dis2[n - 1] + dis3[0]; if (dis1[n - 1] != -1 && dis3[n - 2] != -1 && dis2[0] != -1) { if (res == -1) res = dis1[n - 1] + dis3[n - 2] + dis2[0]; else res = min(res, dis1[n - 1] + dis3[n - 2] + dis2[0]); } cout << res << endl; return 0; }