from collections import deque from heapq import heappop from math import inf, isinf def bfs_dist(graph: list[set[int]], start: int, goal: int) -> int | float: distance = [inf for _ in graph] distance[start] = 0 queue = deque([start]) visited = set() while queue: current = queue.popleft() visited.add(current) for dest in graph[current]: if dest in visited: continue if distance[dest] <= distance[current] + 1: continue queue.append(dest) distance[dest] = distance[current] + 1 return distance[goal] def main(): N, M = map(int, input().split()) graph = [set() for _ in range(N)] for _ in range(M): a, b = map(int, input().split()) graph[a - 1].add(b - 1) graph[b - 1].add(a - 1) if isinf((dist := bfs_dist(graph, 0, N - 1))): print(-1) else: print(dist) if __name__ == "__main__": main()