from heapq import heappop, heappush INF = float('inf') def dijkstra(s, n): dist = [INF] * n hq = [(0, s)] # (distance, node) dist[s] = 0 seen = [False] * n # ノードが確定済みかどうか while hq: dis, v = heappop(hq) if dist[v] < dis: continue seen[v] = True for to, cost in G[v]: if seen[to] == False and dist[v] + cost < dist[to]: dist[to] = dist[v] + cost heappush(hq, (dist[to], to)) return dist N, M = map(int, input().split()) G = [list() for _ in range(N)] for i in range(M): a, b = map(int, input().split()) a-=1;b-=1 G[a].append((b,1)) G[b].append((a,1)) d = dijkstra(0, N) print(-1) if d[-1]==INF else print(d[-1])