#C5396. Detect Cycle in an Undirected Graph
Detect Cycle in an Undirected Graph
Detect Cycle in an Undirected Graph
In this problem, you are given an undirected graph with ( n ) nodes and ( m ) edges. Each edge connects two cities. Your task is to determine whether there exists any cycle in the graph. A cycle exists if you can start at one node, travel along a series of edges, and return to the starting node without reusing any edge. Note that a self-loop (an edge from a node to itself) is considered a cycle.
Input Format:\n- The first line contains two integers ( n ) (the number of nodes) and ( m ) (the number of edges).\n- The next ( m ) lines each contain two integers ( u ) and ( v ) representing an undirected edge between nodes ( u ) and ( v ).
Output Format:\n- Print ( YES ) if the graph contains a cycle, otherwise print ( NO ).
inputFormat
The input is read from stdin
.\n\nThe first line contains two space-separated integers ( n ) and ( m ).\nEach of the next ( m ) lines contains two integers ( u ) and ( v ), representing an undirected edge.
outputFormat
The output is written to stdout
.\n\nOutput a single line: ( YES ) if there exists a cycle in the graph; otherwise, ( NO ).## sample
4 4
1 2
2 3
3 4
4 1
YES