#include using namespace std; void fast_io() { ios::sync_with_stdio(false); std::cin.tie(nullptr); } const int INF = 5e8; vector calc_dist(int s, vector> &g) { int n = g.size(); vector dist(n, INF); dist[s] = 0; deque que; que.push_back(s); while (!que.empty()) { int v = que.front(); que.pop_front(); for (int u : g[v]) { if (dist[u] == INF) { dist[u] = dist[v] + 1; que.push_back(u); } } } return dist; } int main() { fast_io(); 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); } auto dist_0 = calc_dist(0, g); auto dist_n1 = calc_dist(n - 2, g); auto dist_n = calc_dist(n - 1, g); int ans = min(dist_0[n - 2] + dist_n1[n - 1] + dist_n[0], dist_0[n - 1] + dist_n[n - 2] + dist_n1[0]); if (ans > INF) { cout << -1 << endl; } else { cout << ans << endl; } }