from collections import deque from collections import defaultdict def main(): N,M = map(int,input().split()) assert 3<=N<=10**5 assert 0<=M<=min(10**5,N*(N-1)) adj_dict = defaultdict(list) for _ in [0]*M: u,v = map(int,input().split()) assert 1<=u<=N assert 1<=v<=N assert u!=v assert v not in adj_dict[u] adj_dict[u].append(v) # 1から各頂点への距離 dist1 = [-1]*(N+1) dist1[1] = 0 queue = deque([1]) while queue: u = queue.popleft() for v in adj_dict[u]: if dist1[v]==-1: dist1[v] = dist1[u] + 1 queue.append(v) # N-1から各頂点への距離 distN_1 = [-1]*(N+1) distN_1[N-1] = 0 queue = deque([N-1]) while queue: u = queue.popleft() for v in adj_dict[u]: if distN_1[v]==-1: distN_1[v] = distN_1[u] + 1 queue.append(v) # Nから各頂点への距離 distN = [-1]*(N+1) distN[N] = 0 queue = deque([N]) while queue: u = queue.popleft() for v in adj_dict[u]: if distN[v]==-1: distN[v] = distN[u] + 1 queue.append(v) ans = [] if dist1[N-1] != -1 and distN_1[N] != -1 and distN[1] != -1: ans.append(dist1[N-1] + distN_1[N] + distN[1]) if dist1[N] != -1 and distN[N-1] != -1 and distN_1[1] != -1: ans.append(dist1[N] + distN[N-1] + distN_1[1]) if ans == []: print(-1) else: print(min(ans)) if __name__ == "__main__": main()