import heapq def dijkstra2(adjList, s, g): # Initialize the distance from the start node s to all other nodes as infinity distance = [float('inf')] * len(adjList) distance[s] = 0 # Initialize the priority queue with the start node queue = [(0, s)] # (distance, node) while queue: # Get the node with the smallest distance dist, node = heapq.heappop(queue) # If this node has already been processed, then ignore it if dist > distance[node]: continue # Update the distances to the neighboring nodes for neighbor, cost in adjList[node]: new_dist = dist + cost if new_dist < distance[neighbor]: distance[neighbor] = new_dist heapq.heappush(queue, (new_dist, neighbor)) # If the distance to the goal node g is infinity, it means there is no path. if distance[g] == float('inf'): return 1e10 else: return distance[g] N, M = map(int, input().split()) adj_list = [[] for _ in range(N)] for i in range(M): u, v = map(int, input().split()) u -= 1 v -= 1 adj_list[u].append((v, 1)) ans1 = dijkstra2(adj_list, 0, N-2) + dijkstra2(adj_list, N-2, N-1) + dijkstra2(adj_list, N-1, 0) ans2 = dijkstra2(adj_list, 0, N-1) + dijkstra2(adj_list, N-1, N-2) + dijkstra2(adj_list, N-2, 0) ans = min(ans1, ans2) if (ans >= 1e10): print(-1) else: print(ans)