#C12720. Graph Cycle Detection
Graph Cycle Detection
Graph Cycle Detection
Given an undirected graph, determine whether it contains a cycle. The graph is represented by \( n \) vertices (numbered from 0 to \( n-1 \)) and \( m \) edges. An edge connecting a vertex to itself (a self-loop) is also considered a cycle. A cycle exists if there is a path that starts and ends at the same vertex and involves at least one edge. You can use Depth-First Search (DFS) or any other method of your choice.
If a cycle exists, output Cycle detected
; otherwise, output No cycle
.
inputFormat
The input is given from standard input (stdin) in the following format:
- The first line contains two integers \( n \) and \( m \) separated by a space, where \( n \) is the number of vertices and \( m \) is the number of edges.
- Each of the next \( m \) lines contains two integers \( u \) and \( v \), representing an undirected edge between vertex \( u \) and vertex \( v \).
outputFormat
Output a single line to standard output (stdout):
- If the graph contains a cycle, print
Cycle detected
. - If the graph does not contain a cycle, print
No cycle
.
5 5
0 1
1 2
2 3
3 1
3 4
Cycle detected