from collections import deque N,M = map(int,input().split()) l = [[] for _ in range(N)] for _ in range(M): a,b = map(int,input().split()) a -= 1 b -= 1 l[a].append(b) l[b].append(a) INF = 10**18 visited = [INF]*N que = deque([(0,0)]) while que: i,c = que.pop() for j in l[i]: if c+1 < visited[j]: que.append((j,c+1)) visited[j] = c+1 ans = -1 if visited[N-1] != INF: ans = visited[N-1] print(ans)