#C8402. Find the Smallest Cycle in an Undirected Graph
Find the Smallest Cycle in an Undirected Graph
Find the Smallest Cycle in an Undirected Graph
You are given an undirected graph with N nodes and M edges. Your task is to determine the length of the smallest cycle in the graph. A cycle is a path that starts and ends at the same node and contains at least one edge. If there is no cycle in the graph, output -1
.
Note: The cycle length is defined as the number of edges in the cycle. The graph is provided as an edge list and it is guaranteed that there are no duplicate edges. Use the breadth-first search (BFS) algorithm from each node to determine the shortest cycle.
The answer should be computed by processing input from standard input and printing the output to standard output.
inputFormat
The first line contains two integers N and M, representing the number of nodes and edges respectively.
Each of the following M lines contains two integers u and v, which represent an undirected edge between node u and node v.
outputFormat
Print a single integer representing the length of the smallest cycle in the graph. If no cycle exists, print -1
.
5 6
1 2
2 3
3 4
4 5
5 2
3 5
3
</p>