#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // //多分勝ちましたーwww // //うえーい // // using namespace std; typedef long long ll; typedef long double ld; using Graph = vector>; using vi = vector; using vll = vector; using vs = vector; using pii = pair; using pll = pair; template bool chmax(T& a, const T& b) { if (a < b) { a = b;return true; }return false; } template bool chmin(T& a, const T& b) { if (a > b) { a = b;return true; }return false; } #define YN(bool) if(bool){cout<<"Yes"<= 0; i--) #define ALL(box) (box).begin(),(box).end() #define all(box) (box).begin(),(box).end() #define RALL(box) (box).rbegin(),(box).rend() #define ft first #define sd second #define pb push_back //#define mp make_pair #define pqueue priority_queue //sort(box.begin(), box.end()); //sort(box.rbegin(), box.rend()); //vector> box( a , vector( a )); //printf("%.7Lf", n); //reverse(t.begin(), t.end()); //auto It = lower_bound(ALL(box), n);以上 4 //auto It = upper_bound(ALL(box), n);含まない上 7 //cout << box.end() - It ; 末尾までの距離 //cout << It - a.begin() ; 先頭までの距離 //auto It =box.upper_bound( k);set,multiset // vector>> flag(350, vector> 350, vector(350))); //pqueue < int, vector, greater> q; vector> migi(vector>& grid) { int N = grid.size(); // 回転後の新しいグリッドを生成 vector> rotatedGrid(N, vector(N, 0)); // 右に90度回転させる処理 for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { rotatedGrid[i][j] = grid[N - 1 - j][i]; } } return rotatedGrid; } ll sum = 0; ll num = 0; int pum = 0; ll mum = 0; int min1 = 1000000001; int max1 = -2; ll min2 = 9223372036854775807; ll max2 = -10000000000000000; ll MOD1 = 1000000007; ll MOD = 998244353; int Graph_saitan(const vector>& box, int a1, int a2) { queue st; st.push(a1); vector saitan(box.size(),20000000); saitan[a1] = 0; while (!st.empty()) { int p = st.front(); st.pop(); rep(i, box[p].size()) { if (saitan[box[p][i]] > saitan[p] + 1) { st.push(box[p][i]); saitan[box[p][i]] = saitan[p] + 1; } } if (saitan[a2] != 20000000) { return saitan[a2]; } } return -2; } int main() { int a, b; cin >> a >> b; Graph box(a + 1); rep(i, b) { int l, m; cin >> l >> m; l--; m--; box[l].push_back(m); } vector f(3), f2(3); int ans = 20000000; f[0] = Graph_saitan(box, 0, a - 2); f[1] = Graph_saitan(box, a - 2, a - 1); f[2] = Graph_saitan(box, a - 1, 0); f2[0] = Graph_saitan(box, 0, a - 1); f2[1] = Graph_saitan(box, a - 1, a - 2); f2[2] = Graph_saitan(box, a - 2, 0); rep(i, 3) { //cout << f[i] << " "; } rep(i, 3) { //cout << f2[i] << " "; } bool ok=true; int sum1 = 0, sum2 = 0; rep(i, f.size()) { if (f[i] == -2) { ok = false; } sum1 += f[i]; } if (ok) { ans = min(ans, sum1); } ok = true; rep(i, f2.size()) { if (f2[i] == -2) { ok = false; } sum2 += f2[i]; } if (ok) { ans = min(ans, sum2); } if (ans == 20000000) { cout << -1; } else { cout << ans; } }