Fewest hops
Level B. Teaches a vertex domain, reading edges and bfs.
There are n cities (1 ≤ n ≤ 2·10⁵) and m two-way roads (0 ≤ m ≤ 2·10⁵), each joining two cities. Print the fewest roads on a trip from city 1 to city n, or -1 if city n can't be reached.
Input: n and m, then m lines of two cities. Output: one number.
| Input | Output |
|---|---|
5 51 22 33 51 44 5 | 2 |
6 tests · Ctrl+Enter
Hints
domain V = 1..=nmakes cities their own type, and reading(u: V, v: V)rejects a road to city 0 or n + 1.bfsreturns?Intper city:Noneis "unreachable", so the program never compares against-1orINF.- With n = 1 the answer is 0 even with no roads: the start is already the goal.
- Graphs covers reading edges into a domain and
bfs; the graph reference lists the rest.