from collections import deque def solve(N, M, G): def bfs(start): costs = [float("inf")] * N costs[start] = 0 fifo = deque([start]) while fifo: u = fifo.popleft() for v in G[u]: if costs[v] == float("inf"): costs[v] = costs[u] + 1 fifo.append(v) return costs costs1 = bfs(0) costs2 = bfs(N - 2) costs3 = bfs(N - 1) ans = min( costs1[N - 2] + costs2[N - 1] + costs3[0], costs1[N - 1] + costs3[N - 2] + costs2[0], ) if ans == float("inf"): ans = -1 return ans def main(): N, M = map(int, input().split()) G = [[] for _ in range(N)] for _ in range(M): u, v = map(int, input().split()) u -= 1 v -= 1 G[u].append(v) ans = solve(N, M, G) print(ans) if __name__ == "__main__": main()