import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, m = map(int, input().split()) g = [[] for i in range(n)] for i in range(m): a, b = map(int, input().split()) a, b = a-1, b-1 g[a].append(b) g[b].append(a) from collections import deque q = deque([]) q.append(0) dist = [-1]*n dist[0] = 0 while q: v = q.popleft() for u in g[v]: if dist[u] == -1: q.append(u) dist[u] = dist[v]+1 if dist[n-1] == -1: print(-1) else: print(dist[n-1])