from collections import deque N,M=map(int,input().split()) E=[[] for i in range(N+1)] DIS=[1<<30]*(N+1) DIS[1]=0 Q=deque([1]) for i in range(M): x,y=map(int,input().split()) E[x].append(y) E[y].append(x) while Q: x=Q.popleft() for to in E[x]: if DIS[to]>DIS[x]+1: DIS[to]=DIS[x]+1 Q.append(to) if DIS[N]>N+10: print(-1) else: print(DIS[N])