Problem:
Cycle Detection for a Directed Graph

Find a cycle in a directed graph G(V, E).

Input

A directed graph G is given in the following format:

|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1

|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target nodes of i-th edge (directed).

Output

Print 1 if G has cycle(s), 0 otherwise.

Constraints

1 ≤ |V| ≤ 100

0 ≤ |E| ≤ 1,000

si ≠ ti

Sample Input 1

3 3
0 1
0 2
1 2

Sample Output 1

0

Sample Input 2

3 3
0 1
1 2
2 0

Sample Output 2

1

Solution in JAVA (judge verdict: Accepted)

import java.io.*;
import java.util.*;

public class Main {
    private static HashMap<Integer, List<Integer>> graph;
    public static void main(String[] args) throws Exception{
        Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        int V = scanner.nextInt();
        int E = scanner.nextInt();

        graph = new HashMap<>(V);
        for(int i = 0; i < V; ++i){
            graph.put(i, new LinkedList<>());
        }

        for(int i = 0; i < E; ++i){
            int u = scanner.nextInt();
            int v = scanner.nextInt();
            graph.get(u).add(v);
        }

        boolean[] visited = new boolean[V];

        for(int i = 0; i < V; ++i){
            boolean[] recStack = new boolean[V];
            if(!visited[i] && cyclicUtil(i, visited, recStack)){
                System.out.println("1");
                return;
            }
        }

        System.out.println("0");
        return;
    }

    private static boolean cyclicUtil(int cur, boolean[] visited, boolean[] recStack){
        visited[cur] = true;
        recStack[cur] = true;

        for(Integer adj : graph.get(cur)){
            if(recStack[adj]){
                return true;
            }
            else if(!visited[adj] && cyclicUtil(adj, visited, recStack)){
                return true;
            }
        }

        recStack[cur] = false;
        return false;
    }
}