N,M=map(int,input().split())
from heapq import *
G=[[] for i in range(N)]
D=[0]*N
INF=10**17
def ijk(s):
  global D,INF,G
  for i in range(len(G)):
    D[i]=INF
  D[s]=0
  Q=[]
  heapify(Q)
  heappush(Q,(0,s))
  p,v,e=0,0,0
  while len(Q):
    p=heappop(Q)
    v=p[1]
    if D[v]<p[0]:
      continue
    for i in range(len(G[v])):
      e=G[v][i]
      if D[e[0]]>D[v]+e[1]:
        D[e[0]]=D[v]+e[1]
        heappush(Q,(D[e[0]],e[0]))

for i in range(M):
  a,b=map(int,input().split())
  a-=1
  b-=1
  G[a].append((b,1))
  G[b].append((a,1))
ijk(0)
if D[-1]<INF:
  print(D[-1])
else:
  print(-1)