import heapq from collections import deque INF = 10**18 class Dijkstra(): # 全ての辺の距離が1のとき def bfs(self, graph, start, goal=-2): N = len(graph) is_visited = [False]*N is_visited[start] = True dists = [INF]*N dists[start] = 0 que = deque([(start, 0)]) while que: p, d = que.popleft() for next in graph[p]: if not is_visited[next]: que.append((next, d+1)) dists[next] = d+1 is_visited[next] = True if goal == next: return dists return dists def dijkstra(self, graph, start): N = len(graph) dists = [INF for _ in range(N)] dists[start] = 0 is_done = [False for _ in range(N)] hp = [] # 経路復元が必要な場合 prev = [-1 for _ in range(N)] heapq.heappush(hp, (dists[start], start)) while hp: min_dist, min_v = heapq.heappop(hp) if is_done[min_v]: continue is_done[min_v] = True # 隣接リスト形式でコストが無いなら、ここのcostを削除することに注意 for to, d in graph[min_v]: # 隣接リスト形式でコストが無いなら、ここのコストを1に変更することに注意 dist = dists[min_v] + d if dist < dists[to]: dists[to] = dist prev[to] = min_v heapq.heappush(hp, (dists[to], to)) return dists, prev # 後ろから順になっている事に注意 def get_path(self, prev, end): path = [] p = end while prev[p] != -1: path.append(p) p = prev[p] path.append(p) return path N, M = map(int, input().split()) graph = [[] for _ in range(N)] for _ in range(M): ui, vi = map(int, input().split()) ui -= 1 vi -= 1 graph[ui].append((vi, 1)) dijk = Dijkstra() dist_from_0, _ = dijk.dijkstra(graph, 0) dist_from_N1, _ = dijk.dijkstra(graph, N-2) dist_from_N, _ = dijk.dijkstra(graph, N-1) ans = INF ans = min(ans, dist_from_0[N-2] + dist_from_N1[N-1 ]+ dist_from_N[0]) ans = min(ans, dist_from_0[N-1] + dist_from_N[N-2] + dist_from_N1[0]) if ans == INF: print(-1) else: print(ans)