n,m=map(int,input().split()) e=[[] for i in range(n)] for i in range(m): a,b=map(int,input().split()) a-=1 b-=1 e[a]+=[b] X=10**10 v=[X]*n v[0]=0 q=[0] for s in q: for t in e[s]: if v[t]==X: v[t]=v[s]+1 q+=[t] stot1=v[n-2] stot2=v[n-1] v=[X]*n v[n-2]=0 q=[n-2] for s in q: for t in e[s]: if v[t]==X: v[t]=v[s]+1 q+=[t] t1tos=v[0] t1tot2=v[n-1] v=[X]*n v[n-1]=0 q=[n-1] for s in q: for t in e[s]: if v[t]==X: v[t]=v[s]+1 q+=[t] t2tos=v[0] t2tot1=v[n-2] ans=min(stot1+t1tot2+t2tos,stot2+t2tot1+t1tos) print(ans if ans