#K68607. Cycle Detection in Undirected Graphs
Cycle Detection in Undirected Graphs
Cycle Detection in Undirected Graphs
You are given one or more undirected graphs. For each graph, determine whether it contains a cycle.
A cycle in an undirected graph is a path of edges and vertices in which a vertex is reachable from itself by traversing a set of distinct vertices (except the start/end vertex) and edges, with at least three vertices involved. Formally, if the graph has vertices \(V\) and edges \(E\), a cycle exists if there is a sequence \(v_0, v_1, \dots, v_k\) (with \(k \geq 3\)) such that \(v_0 = v_k\) and all other vertices are distinct, and each consecutive pair \((v_i, v_{i+1}) \in E\).
Your task is to implement a cycle detection algorithm using Depth-First Search (DFS) that checks each connected component of the graph. Report "Cycle Detected" if a cycle is found, otherwise output "No Cycle".
inputFormat
The input is read from standard input (stdin) and has the following format:
T N1 M1 u1 v1 ... uM1 vM1 N2 M2 ...
Here, T
is the number of test cases. For each test case:
N
is the number of vertices (vertices are numbered from 0 to N-1).M
is the number of edges.- Next
M
lines each contains two integersu
andv
indicating an undirected edge between verticesu
andv
.
outputFormat
For each test case, output a single line to standard output (stdout):
- Output "Cycle Detected" if the graph contains a cycle.
- Output "No Cycle" if there is no cycle in the graph.
2
3 3
0 1
1 2
2 0
4 2
0 1
2 3
Cycle Detected
No Cycle
</p>