Problems > The Shortest Loop

The Shortest Loop

Difficulty: 2000 6000 ms 128 MB

bfs graphs

Print the length (number of edges) of the shortest cycle (girth) in an undirected simple graph, or −1 if it is acyclic.

Input: the first line has N and M; each of the next M lines has an edge u v.

Output: the girth, or −1.

Constraints:

  • 1 ≤ N ≤ 103
  • 0 ≤ M ≤ 2×103

Sample Tests

Input 1
4 4
1 2
2 3
3 4
4 1
Output 1
4
Input 2
3 2
1 2
2 3
Output 2
-1

Read the Editorial

Discussion (opens after you solve — no spoilers before)

No comments yet.

Submit Your Solution

Log in or create a free account to run and submit code.