A transit map has n stations connected by two-way corridors. Every corridor takes exactly one hop to traverse. Given a start station and a destination station, determine the minimum number of hops needed to travel from start to destination.
If the destination cannot be reached from the start, report -1. If the start and destination are the same station, the answer is 0.
Line 1: two integers n and m — the number of stations and the number of corridors.
Next m lines: two integers u v (0-indexed) meaning there is a two-way corridor between station u and station v.
Last line: two integers s t — the start station and the destination station.
A single integer: the minimum number of hops from s to t, or -1 if t is unreachable from s.
Two equal-length routes
Input
4 4 0 1 1 3 0 2 2 3 0 3
Expected
2
Explanation
Both 0\u21921\u21923 and 0\u21922\u21923 use two corridors, so the fewest hops from 0 to 3 is 2.
Disconnected destination
Input
5 2 0 1 2 3 0 4
Expected
-1
Explanation
Station 4 is isolated (no corridor touches it), so it cannot be reached from 0 and the answer is -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →