import collections N,M = map(int, input().split()) L = [[] for _ in range(N+1)] for i in range(M): a,b = map(int, input().split()) L[b].append(a) L[a].append(b) PASS = [False]*(N+1) d = collections.deque() d.append((1,0)) while len(d): p,cnt=d.popleft() if p==N: print(cnt) exit() for n in L[p]: if PASS[n]==False: PASS[n]=True d.append((n,cnt+1)) print(-1)