from collections import deque N,M = map(int,input().split()) E = [[] for i in range(N)] for _ in range(M): a,b = map(int,input().split()) E[a-1].append(b-1) E[b-1].append(a-1) q = deque() q.append(0) dp = [0]*N while q: x = q.pop() for y in E[x]: if y != 0 and dp[y] == 0: dp[y] = dp[x]+1 q.appendleft(y) if dp[-1] == 0: ans = -1 else: ans = dp[-1] print(ans)