Directed cycles with DFS · Compiler

Directed cycles with DFS

Run recursive DFS on a directed graph, starting a search at each unvisited vertex in increasing ID order. On entry mark the vertex active. Examine its outgoing neighbors in increasing ID order. Recurse immediately on an unvisited neighbor and mark the current vertex finished only after all its neighbors are examined. Stop at the first edge to an active neighbor.

Input
The first line contains n m. Vertices are numbered 0 through n-1 (1 <= n <= 50, 0 <= m <= 200). Each of the next m lines contains u v for an edge from u to v. Endpoints differ and each ordered pair occurs at most once.
Output
Print the destination vertex ID of the first edge to an active neighbor, or -1 if no such edge exists.

Compiler Explorer runs your code when you run or check it.

Loading your exercise draft…