from collections import deque def bfs(s): dq=deque() dq.append([s,0]) high=[10**9 for _ in range(N)] high[s]=0 while len(dq)!=0: p,h=dq.popleft() for e in edge[p]: if high[e]==10**9: dq.append([e,h+1]) high[e]=h+1 return high N,M=map(int,input().split()) edge=[[] for _ in range(N)] for i in range(M): u,v=map(int,input().split()) u-=1 v-=1 edge[u].append(v) dist0=bfs(0) distn_=bfs(N-2) distn=bfs(N-1) ans=min(dist0[N-2]+distn_[N-1]+distn[0],dist0[N-1]+distn[N-2]+distn_[0]) if ans>10**9: print(-1) else: print(ans)