from collections import deque N, M = map(int, input().split()) G = [[] for _ in range(N)] for _ in range(M): u, v = map(int, input().split()) G[u-1].append(v-1) visited = [[-1]*(1<<2) for _ in range(N)] visited[0][0] = 0 que = deque() que.append((0, 0)) while que: n, bit = que.popleft() for v in G[n]: nbit = bit if v == N-2: nbit |= 1<<0 if v == N-1: nbit |= 1<<1 if visited[v][nbit] == -1: visited[v][nbit] = visited[n][bit]+1 que.append((v, nbit)) print(visited[0][-1])