A sensor network is a simple undirected graph on n sensors numbered 1 through n, joined by cables (no self-cables, and at most one cable between any pair of sensors). A loop is a cycle: a sequence of distinct sensors a1, a2, ..., ak (with k >= 3) such that consecutive sensors are joined by a cable and the last sensor is joined back to the first.
Report the number of cables in the shortest loop (its length). If the network contains no loop at all, report -1.
Line 1: two integers n and m.
Next m lines: two integers u and v, a cable between sensors u and v.
A single integer: the length of the shortest loop, or -1 if there is none.
Example 1
Input
5 6 1 2 2 3 3 1 3 4 4 5 5 3
Expected
3
Explanation
Two triangles share sensor 3; the shortest loop uses 3 cables.
Example 2
Input
4 4 1 2 2 3 3 4 4 1
Expected
4
Explanation
The only loop is the 4-cable square 1-2-3-4-1, so the answer is 4.
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 →