#K9406. Cycle Detection in Directed Graph
Cycle Detection in Directed Graph
Cycle Detection in Directed Graph
You are given a directed graph with ( n ) vertices and ( m ) edges. The vertices are numbered from 1 to ( n ). Your task is to determine whether the graph contains a cycle. If a cycle exists, output the sequence of vertices forming the cycle (with the first and last vertex being the same). Otherwise, print "No cycle".
A cycle is defined as a non-empty sequence of vertices ( v_1, v_2, \ldots, v_k ) (with ( k \ge 2 )) such that there is an edge from ( v_i ) to ( v_{i+1} ) for ( 1 \le i < k ) and an edge from ( v_k ) back to ( v_1 ).
Example: For example, if ( n = 4, m = 4 ) and the directed edges are:
1 2 2 3 3 4 4 2
Then one valid cycle is: 2 3 4 2.
inputFormat
The input is read from standard input (stdin). The first line contains two integers ( n ) and ( m ), representing the number of vertices and edges respectively. The following ( m ) lines each contain two integers ( u ) and ( v ) representing a directed edge from vertex ( u ) to vertex ( v ).
outputFormat
Output to standard output (stdout). If a cycle is detected, print the vertices in the cycle separated by a single space (the cycle should start and end at the same vertex). If no cycle exists, print "No cycle".## sample
4 4
1 2
2 3
3 4
4 2
2 3 4 2