A social network has n members numbered 1 through n. Some pairs of members are mutual friends. The degrees of separation between two members is the minimum number of friendship links you must cross to travel from one to the other.
Given a start member s and a target member t, report their degrees of separation. If s equals t the answer is 0. If there is no chain of friendships connecting them, report -1.
Line 1: two integers n and m.
Next m lines: two integers u and v, a mutual friendship between members u and v.
Last line: two integers s and t.
A single integer: the degrees of separation, or -1 if t is unreachable from s.
Example 1
Input
6 5 1 2 2 3 3 4 1 5 5 4 1 4
Expected
2
Explanation
The route 1-5-4 crosses two links, which is shorter than 1-2-3-4 (three links), so the answer is 2.
Example 2
Input
4 2 1 2 3 4 1 4
Expected
-1
Explanation
Member 1 is in {1,2} and member 4 is in {3,4}; there is no connecting chain, so 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 →