#C2958. Detecting Cycles in a Directed Graph
Detecting Cycles in a Directed Graph
Detecting Cycles in a Directed Graph
You are given a directed graph with \(N\) vertices and \(M\) edges. Your task is to determine whether the graph contains a cycle. A cycle is defined as a non-empty sequence of edges \( (v_1, v_2), (v_2, v_3), \dots, (v_k, v_1) \) where \(k \ge 1\), meaning that there is a path that starts and ends at the same vertex.
If the graph contains at least one cycle, print YES
; otherwise, print NO
.
inputFormat
The first line of input contains a single integer \(T\) (the number of test cases). Each test case is described as follows:
- The first line contains two space-separated integers \(N\) and \(M\) representing the number of vertices and edges respectively.
- The next \(M\) lines each contain two space-separated integers \(u\) and \(v\) denoting a directed edge from vertex \(u\) to vertex \(v\).
It is guaranteed that \(1 \leq u, v \leq N\).
outputFormat
For each test case, output a single line containing either YES
if the graph contains a cycle, or NO
otherwise.
4
4 4
1 2
2 3
3 4
4 2
3 2
1 2
2 3
1 1
1 1
5 4
1 2
2 3
3 4
4 5
YES
NO
YES
NO
</p>