N,M=map(int,input().split()) G=[[] for i in range(N)] for i in range(M): a,b=map(int,input().split()) G[a-1].append(b-1) from collections import deque S=deque() dist=[10**10]*N dist[0]=0 S.append(0) while S: x=S.popleft() for y in G[x]: if dist[y]<10**8: continue dist[y]=dist[x]+1 S.append(y) L1=[10**10]*N L1[N-1]=0 S=deque() S.append(N-1) while S: x=S.popleft() for y in G[x]: if L1[y]<10**8: continue L1[y]=L1[x]+1 S.append(y) L2=[10**10]*N L2[N-2]=0 S=deque() S.append(N-2) while S: x=S.popleft() for y in G[x]: if L2[y]<10**8: continue L2[y]=L2[x]+1 S.append(y) result=10**10 ans=dist[N-1]+L1[N-2]+L2[0] result=min(result,ans) ans=dist[N-2]+L2[N-1]+L1[0] result=min(result,ans) print(result)