#include using namespace std; template using min_priority_queue = priority_queue,greater>; template void printv(vector &v){ bool b = false; for(auto i : v){ if(b) cout << " "; else b = true; cout << i; } cout << endl; } template bool chmin(T &a, const T& b) { if (a > b) { a = b; // aをbで更新 return true; } return false; } template bool chmax(T &a, const T& b) { if (a < b) { a = b; // aをbで更新 return true; } return false; } void yn(bool b){ if(b) cout << "Yes" << endl; else cout << "No" << endl; } bool debug; bool randomInput; void input(){ if(debug && randomInput){ } else{ } return; } void calc(){ 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); } vector X = {0, N-2, N-1}; int INF = 1001002003; vector> D(3, vector(3, INF)); for(int i = 0; i < 3; i++){ int s = X[i]; vector d(N, INF); d[s] = 0; queue q; q.push(s); while(q.size()){ int pos = q.front(); q.pop(); for(int k : G[pos]){ if(chmin(d[k], d[pos]+1)){ q.push(k); } } } for(int j = 0; j < 3; j++){ D[i][j] = d[X[j]]; } } int64_t a1 = D[0][1] + D[1][2] + D[2][0]; int64_t a2 = D[0][2] + D[2][1] + D[1][0]; int64_t ans = min(a1, a2); if(ans >= INF) ans = -1; cout << ans << endl; return; } int64_t ansSimple; void calcSimple(){ return; } void calc1(){ int t; cin >> t; for(int i = 0; i < t; i++){ input(); calc(); calcSimple(); } } int main(){ debug = 0; randomInput = 0; srand(time(NULL)); cout << fixed << setprecision(12); if(debug){ calc1(); } else{ input(); calc(); } return 0; } //