#include #include #define OVERLOAD_REP(_1, _2, _3, name, ...) name #define REP1(i,n) for (auto i = std::decay_t{}; (i) != (n); ++(i)) #define REP2(i,l,r) for (auto i = (l); (i) != (r); ++(i)) #define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__) #define all(a) (a).begin(),(a).end() #define rall(a) (a).rbegin(),(a).rend() using namespace std; using namespace atcoder; using ll = long long; using ull = unsigned long long; using P = pair; using LP = pair; using SP = pair; using vi = vector; using vl = vector; using vs = vector; using vc = vector; using mint1 = modint1000000007; using mint9 = modint998244353; const int INF = 1e9; const long long LINF = 1e18; const int di[] = {0,1,0,-1,-1,1,-1,1}; const int dj[] = {1,0,-1,0,1,1,-1,-1}; template inline bool chmin(T& a, T b){if(a>b){a=b;return true;}return false;} template inline bool chmax(T& a, T b){if(a dist_bfs (int s) { vector res(n , LINF); queue qe; qe.push(s); res[s] = 0; while(!qe.empty()) { int pos = qe.front(); qe.pop(); for(int u : g[pos]) { if(res[u] != LINF) continue; res[u] = res[pos]+1; qe.push(u); } } return res; } bool bipartite_bfs () { vector color(n , -1); bool isBipartite = true; for(int s = 0; s < n; s++) { if(color[s] != -1) continue; queue qe; qe.push(s); color[s] = 0; while(!qe.empty()) { int pos = qe.front(); qe.pop(); for(int u : g[pos]) { if(color[u] != -1) { if(color[u] == color[pos]) isBipartite = false; continue; } color[u] = 1-color[pos]; qe.push(u); } } } return isBipartite; } public: int n , m; vector> g; UGraph (int nn) { g = vector>(nn); n = nn; } void merge (int u , int v) { g[u].push_back(v); //g[v].push_back(u); } vector dist(int s) { return dist_bfs(s); } bool bipartite () { return bipartite_bfs(); } }; int main () { int n , m; cin >> n >> m; UGraph g(n); rep(i , m) { int u , v; cin >> u >> v; u--; v--; g.merge(u , v); } auto d0 = g.dist(0) , dn2 = g.dist(n-2) , dn1 = g.dist(n-1); long long res = LINF; chmin(res , d0[n-2]+dn2[n-1]+dn1[0]); chmin(res , d0[n-1]+dn1[n-2]+dn2[0]); if(res == LINF) res = -1; cout << res << endl; return 0; }