#include #include #include using namespace std; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int N, M, u, v, i; cin >> N >> M; vector> edges(N, vector()); for (i = 0; i != M; ++i) cin >> u >> v, edges[u - 1].push_back(v - 1); vector> dist(4, vector(N, -1)); queue> q; q.emplace(0, 0), dist[0][0] = 0; while (!q.empty()) { for (i = 0; i != edges[q.front().second].size(); ++i) { if (dist[q.front().first][edges[q.front().second][i]] == -1) q.emplace(q.front().first, edges[q.front().second][i]), dist[q.front().first][edges[q.front().second][i]] = dist[q.front().first][q.front().second] + 1; if (edges[q.front().second][i] == N - 1 && dist[q.front().first | 1][edges[q.front().second][i]] == -1) q.emplace(q.front().first | 1, edges[q.front().second][i]), dist[q.front().first | 1][edges[q.front().second][i]] = dist[q.front().first][q.front().second] + 1; if (edges[q.front().second][i] == N - 2 && dist[q.front().first | 2][edges[q.front().second][i]] == -1) q.emplace(q.front().first | 2, edges[q.front().second][i]), dist[q.front().first | 2][edges[q.front().second][i]] = dist[q.front().first][q.front().second] + 1; } q.pop(); } cout << dist[3][0] << '\n'; return 0; }