#K52722. Cycle Detection in Directed Graphs

    ID: 29373 Type: Default 1000ms 256MiB

Cycle Detection in Directed Graphs

Cycle Detection in Directed Graphs

You are given a directed graph with n nodes and m edges. Your task is to determine whether the graph contains a cycle. A cycle exists if, starting from some vertex, there is a way to follow the directed edges and return to the starting vertex.

The input consists of multiple test cases. For each test case, you are provided with the number of nodes and edges, followed by a list of directed edges. Print "YES" if a cycle exists in the graph, otherwise print "NO" for that test case.

Hint: A common approach is to use Depth First Search (DFS) along with a recursion stack to detect cycles.

All formulas in this description follow the Latex format. For example, the number of nodes is denoted by \(n\) and the number of edges by \(m\).

inputFormat

The input is read from stdin and has the following format:

T
n1 m1
u1 v1
... 
 um1 vm1
n2 m2
... 

Where:

  • T is the number of test cases.
  • For each test case, the first line contains two integers \(n\) and \(m\), the number of nodes and edges respectively.
  • The next \(m\) lines each contain two integers \(u\) and \(v\) representing a directed edge from node \(u\) to node \(v\).

outputFormat

For each test case, output a single line containing either "YES" if the graph contains a cycle, or "NO" if it does not. The output is written to stdout.

## sample
2
4 5
0 1
0 2
1 2
2 0
2 3
3 3
0 1
1 2
2 0
YES

YES

</p>