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 C# (judge verdict: Accepted)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split(' ');
            int V = int.Parse(input[0]);
            int E = int.Parse(input[1]);

            Dictionary<int, List<int>> G = new Dictionary<int, List<int>>();
            for (int i = 0; i < V; i++) G.Add(i, new List<int>());

            for (int i = 0; i < E; i++)
            {
                input = Console.ReadLine().Split(' ');
                int s = int.Parse(input[0]);
                int t = int.Parse(input[1]);

                G[s].Add(t);
            }

            Console.WriteLine(IsDAG(G) ? "0" : "1");
        }

        static bool IsDAG(Dictionary<int, List<int>> G)
        {
            int n = G.Count;

            int[] color = new int[n];

            for (int i = 0; i < n; i++)
            {
                if (color[i] == 0 && !Visit(G, i, color)) return false;
            }
            return true;
        }

        static bool Visit(Dictionary<int, List<int>> G, int v, int[] color)
        {
            color[v] = 1;

            foreach (var e in G[v])
            {
                if (color[e] == 2) continue;
                if (color[e] == 1) return false;
                if (!Visit(G, e, color)) return false;
            }

            color[v] = 2;
            return true;
        }
    }
}