A relay network has n towers, numbered 1 to n, and m two-way wires between pairs of towers. A signal originates at a chosen source tower s and spreads outward: from any tower holding the signal, it reaches every directly-wired neighbor one hop later.
If the signal eventually reaches every one of the n towers, report the number of hops needed for the LAST tower to receive it (the maximum shortest-path distance from s to any tower). If at least one tower can never receive the signal, report -1 instead.
Line 1: two integers n and m — number of towers (1-indexed) and number of wires.
Next m lines: two integers u v — an undirected wire between tower u and tower v.
Last line: one integer s — the source tower.
A single integer: the maximum hop distance from s to reach every tower, or -1 if some tower is unreachable.
Example 1
Input
4 3 1 2 2 3 3 4 1
Expected
3
Explanation
From tower 1: dist 1=0, 2=1, 3=2, 4=3. All reachable, farthest is 3 hops away.
Example 2
Input
3 1 1 2 1
Expected
-1
Explanation
Tower 3 has no wire at all, so it never receives the signal: output -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 →