#C1257. Cycle Detection in an Undirected Graph

    ID: 42011 Type: Default 1000ms 256MiB

Cycle Detection in an Undirected Graph

Cycle Detection in an Undirected Graph

You are given an undirected graph represented as an adjacency list. Your task is to determine whether the graph contains any cycle. A cycle is defined as a sequence of vertices \(v_0, v_1, \ldots, v_k\) (with \(k \ge 3\)) such that \(v_0 = v_k\) and all edges \(\{v_i, v_{i+1}\}\) for \(0 \le i < k\) exist in the graph.

The input begins with an integer \(T\) representing the number of test cases. Each test case starts with two integers \(N\) and \(M\) representing the number of nodes and the number of edges, respectively. Nodes are labeled from 0 to \(N-1\). Then, \(M\) lines follow, each containing two integers \(u\) and \(v\) indicating that there is an undirected edge between node \(u\) and node \(v\).

For each test case, output Yes if the graph contains a cycle and No otherwise.

inputFormat

The first line of input contains the integer \(T\) (number of test cases). Each test case is formatted as follows:

  • The first line contains two integers \(N\) and \(M\), where \(N\) is the number of nodes and \(M\) is the number of edges.
  • The next \(M\) lines each contain two integers \(u\) and \(v\) representing an edge between nodes \(u\) and \(v\).

Input is provided via standard input (stdin).

outputFormat

For each test case, output a single line containing either Yes if the graph contains a cycle, or No otherwise. Output should be written to standard output (stdout).

## sample
2
4 4
0 1
1 2
2 3
3 0
3 2
0 1
1 2
Yes

No

</p>