N,M = map(int,input().split()) G = [[] for i in range(N)] for _ in range(M): a,b = map(int,input().split()) G[a - 1].append(b - 1) G[b - 1].append(a - 1) from collections import deque q = deque([]) q.append([0, -1, 0]) visited = [False] * N while q: v,p,c = q.popleft() if visited[v]: continue visited[v] = True if v == N - 1: print(c) break for child in G[v]: if child == p: continue if visited[child]: continue q.append([child, v, c + 1]) else: print(-1)