#K58827. Cycle Detection in an Undirected Graph

    ID: 30729 Type: Default 1000ms 256MiB

Cycle Detection in an Undirected Graph

Cycle Detection in an Undirected Graph

Given an undirected graph with ( n ) vertices represented as an adjacency list, determine whether the graph contains a cycle.

A cycle in a graph is a non-empty path in which the first and last vertices are the same, and no edge is repeated.

You are required to read the graph from standard input and print "True" if a cycle is detected, otherwise print "False". Use depth-first search (DFS) to detect cycles in the graph.

inputFormat

The input is read from standard input (stdin). The first line contains an integer ( n ), the number of vertices in the graph.

The next ( n ) lines describe the adjacency list of the graph. Each line corresponds to a vertex (0-indexed) and contains space-separated integers representing the neighbors of that vertex.

If a vertex has no neighbors, the corresponding line will be empty.

outputFormat

Output to standard output (stdout) a single line: "True" if the graph contains a cycle, and "False" otherwise.## sample

4
1 2
0 2
0 1 3
2
True