import std; void main () { int N, M; readln.read(N, M); int[][] graph = new int[][](N, 0); foreach (i; 0..M) { int u, v; readln.read(u, v); u--, v--; graph[u] ~= v; } solve(N, M, graph); } void solve (int N, int M, int[][] graph) { /* 最適ルートは 1 -> N-1 -> N -> 1 or 1 -> N -> N-1 -> 1のどちらか。これを全部BFSで調べる */ int[] visited = new int[](N); DList!int Q; void BFS (int begin) { visited[] = int.max; visited[begin] = 0; Q.insertBack(begin); while (!Q.empty) { auto head = Q.front; Q.removeFront; foreach (to; graph[head]) { if (visited[to] == int.max) { visited[to] = visited[head] + 1; Q.insertBack(to); } } } } int ans = int.max; { // 1 -> N-1 -> N -> 1 long candi = 0; BFS(0); candi += visited[N-2]; BFS(N-2); candi += visited[N-1]; BFS(N-1); candi += visited[0]; if (candi < int.max) ans = min(ans, cast(int) candi); } { // 1 -> N -> N-1 -> 1 long candi = 0; BFS(0); candi += visited[N-1]; BFS(N-1); candi += visited[N-2]; BFS(N-2); candi += visited[0]; if (candi < int.max) ans = min(ans, cast(int) candi); } if (ans == int.max) { writeln(-1); } else { writeln(ans); } } void read (T...) (string S, ref T args) { auto buf = S.split; foreach (i, ref arg; args) { arg = buf[i].to!(typeof(arg)); } }