Problem 163
Shortest Path in an Unweighted Graph
Easy · 10 pts · Graph, Breadth-First Search
Problem
You are given an undirected graph with N nodes labelled 1 to N and M edges, all of the same length. Print the minimum number of edges on a path from node 1 to node N, or -1 if node N cannot be reached from node 1. If N is 1, the answer is 0. Breadth-first search finds shortest paths in unweighted graphs: it explores nodes in order of their distance from the start, so the first time it reaches node N, it has used the fewest possible edges.
Input
First line: integers N (nodes, labelled 1..N) and M (edges). Next M lines: an edge u v.
Output
Print the length of the shortest path, or -1.
Constraints
1 <= N <= 100000; 0 <= M <= 200000
Example input
4 4 1 2 2 4 1 3 3 2
Example output
2
Explanation
Node 1 is connected to nodes 2 and 3, and node 2 is connected to node 4. The path 1 → 2 → 4 uses 2 edges, and there is no direct edge from 1 to 4, so the answer is 2.