import sys #sys.setrecursionlimit(10 ** 6) INF = float('inf') #10**20に変えるのもあり MOD = 10**9 + 7 MOD2 = 998244353 def solve(): def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def LC(): return list(input()) def IC(): return [int(c) for c in input()] def MI(): return map(int, sys.stdin.readline().split()) N,M = MI() Graph = [[] for n in range(N + 1)] for i in range(M): A, B = MI() Graph[A].append((B,1)) Graph[B].append((A,1)) from heapq import heappush, heappop def dijkstra(s, n): # (始点, ノード数) dist = [INF] * n hq = [(0, s)] # (distance, node) dist[s] = 0 seen = [False] * n # ノードが確定済みかどうか while hq: v = heappop(hq)[1] # ノードを pop する if seen[v]: continue seen[v] = True for to, cost in Graph[v]: # ノード v に隣接しているノードに対して if seen[to] == False and dist[v] + cost < dist[to]: dist[to] = dist[v] + cost heappush(hq, (dist[to], to)) return dist Dist = dijkstra(1, N+1) #print(Dist) if(Dist[N] == INF): print(-1) else: print(Dist[N]) return solve()