import sys
#sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10**9 + 7
MOD2 = 998244353
from collections import defaultdict
def ceil(A,B):
    return -(-A//B)
import heapq
def dijkstra(edges: "List[List[(cost, to)]]", start_node: int) -> list:
    hq = []
    heapq.heapify(hq)
    # Set start info
    dist = [INF] * len(edges)
    heapq.heappush(hq, (0, start_node))
    dist[start_node] = 0
    # dijkstra
    while hq:
        # ------------------------------------------- タイミング1
        min_cost, now = heapq.heappop(hq)
        # ------------------------------------------- タイミング2
        if min_cost > dist[now]:
            continue
        for cost, next in edges[now]:
            if dist[next] > dist[now] + cost:
                dist[next] = dist[now] + cost
                heapq.heappush(hq, (dist[next], next))
            # --------------------------------------- タイミング3
    return dist
def solve():
    def II(): return int(sys.stdin.readline())
    def LI(): return list(map(int, sys.stdin.readline().split()))
    def LC(): return list(sys.stdin.readline().rstrip())
    def IC(): return [int(c) for c in sys.stdin.readline().rstrip()]
    def MI(): return map(int, sys.stdin.readline().split())
    N,M = MI()
    Edge = [[] for _ in range(4*N)]
    for i in range(M):
        U,V = MI()
        U-=1
        V-=1
        for i in range(4):
            Edge[i*N+U].append((1,i*N+V))
    Edge[N-2].append((0,2*N-2))
    Edge[N-1].append((0,3*N-1))
    Edge[2*N-1].append((0,4*N-1))
    Edge[3*N-2].append((0,4*N -2))
    Dist = dijkstra(Edge,0)
    #print(Dist)

    if(Dist[3*N]==INF):
        print(-1)
    else:
        print(Dist[3*N])
    return
solve()