A cycle in a digraph is a sequence of vertices $v_1, v_2, \dots, v_{k}$ such that $(v_{i}, v_{i+1}) \in E$ for all $0 \leq i \leq k-1$ and $(v_k, v_1) \in E$. Here is an example of a directed graph with a cycle:
The number $k$ is the length of the cycle. We explicitly allow cycles of length 2:
and even of length $1$, also called self-loops.
Here is an example of a digraph without a cycle:
Definition A digraph without a cycle is called acyclic. We abbreviate directed acyclic graph by the acronym DAG.
We can use depth-first search to detect cycles. When we explore a new edge $(u,v)$ and $v$ has already been visited, this can be a cycle but does not have to. It is a cycle of $v$ is still on the stack. Thus, we need an additional boolean array is_on_stack that lets us quickly look up whether a vertex is on the stack. When the depth-first search with starting point $s$ returns without having found a cycle, we cannot yet conclude that $G$ is acyclic; it might be that no cycle is reachable from $s$; we need to proceed to the next unvisited vertex $s'$ and now start a depth-first search from $s'$. Thus, we need to have yet another for loop to wrap our depth-first search in.
Problem Write a program that reads a digraph and outputs whether it has a cycle or not.
Input: The first line contains two integers $n$ and $m$, the number of vertices and edges, respectively. The following $m$ lines contain two integers $u$ and $v$ with $1 \leq u, v \leq n$, meaning that $(u,v)$ is an edge.
Output: a single line, containing the words has a cycle or is acyclic.
7 9 1 2 2 3 3 4 3 7 4 6 4 7 5 2 5 3 6 1
has a cycle
8 10 1 2 1 5 1 6 2 3 3 4 3 7 4 6 5 6 8 2 8 3
is acyclic
Problem Extend your solution to not only say whether $G$ is acyclic or not: in the case that it has a cycle, it should output a cycle.