#K48797. Shortest Cycle in an Undirected Graph
Shortest Cycle in an Undirected Graph
Shortest Cycle in an Undirected Graph
You are given an undirected graph with \( n \) vertices and \( m \) edges. Your task is to determine whether the graph contains any cycle. If a cycle exists, output the length of the shortest cycle; otherwise, output "NO".
A cycle is defined as a sequence of vertices \( v_1, v_2, \dots, v_k \) (with \( k \ge 1 \)) such that there is an edge between \( v_i \) and \( v_{i+1} \) for \( 1 \le i < k \) and an edge between \( v_k \) and \( v_1 \). Note that a self-loop (an edge from a vertex to itself) is considered a cycle of length 1.
If there is more than one cycle, you must output the length of the one with the smallest number of edges.
inputFormat
The input is given from standard input as follows:
The first line contains two integers ( n ) and ( m ) (the number of vertices and edges, respectively).
Each of the next ( m ) lines contains two integers ( u ) and ( v ) indicating an undirected edge between vertices ( u ) and ( v ) (( 1 \le u,v \le n )).
outputFormat
Print a single line to standard output. If a cycle exists, output the length of the shortest cycle. Otherwise, output "NO".## sample
4 4
1 2
2 3
3 4
4 2
3