import std, core.bitop; string[] _R; void readM(T)(ref T x) { while (_R.empty) { _R = readln.chomp.split; } x = _R.front.to!T; _R.popFront; } bool chmin(T)(ref T A, T B) { if (A > B) { A = B; return true; } else { return false; } } bool chmax(T)(ref T A, T B) { if (A < B) { A = B; return true; } else { return false; } } int lowerBound(T)(T[] A, T x) { int lo = -1, hi = cast(int)(A.length); while (hi - lo > 1) { int mid = lo + hi >> 1; (A[mid] < x ? lo : hi) = mid; } return hi; } int upperBound(T)(T[] A, T x) { int lo = -1, hi = cast(int)(A.length); while (hi - lo > 1) { int mid = lo + hi >> 1; (A[mid] > x ? hi : lo) = mid; } return hi; } enum INF = 10 ^^ 8; int N, M; int[][] G; int[] BFS(int s) { auto dist = new int[N]; dist[] = INF; dist[s] = 0; int[] que; que ~= s; while (!que.empty) { int u = que.front; que.popFront; if (!u) { continue; } foreach (v; G[u]) { if (chmin(dist[v], dist[u] + 1)) { que ~= v; } } } return dist; } void main() { N.readM; M.readM; G = new int[][](N, 0); foreach (i; 0 .. M) { int u, v; u.readM; v.readM; --u, --v; G[u] ~= v; G[v] ~= u; } auto A = BFS(N - 2); auto B = BFS(N - 1); int ans = INF; chmin(ans, A[0] + A[N - 1] + B[0]); chmin(ans, B[0] + B[N - 2] + A[0]); if (ans == INF) { ans = -1; } writeln(ans); }