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: Wrong Answer)

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

public class P
{
    public List<int> from { get; set; }
    public List<int> to { get; set; }
}

public class Hello
{
    public static void Main()
    {
        string[] line = Console.ReadLine().Trim().Split(' ');
        var n = int.Parse(line[0]);
        var e = int.Parse(line[1]);
        var d = new Dictionary<int, P>();
        for (int i = 0; i < n; i++) d[i] = new P { from = new List<int>(), to = new List<int>() };
        for (int i = 0; i < e; i++)
        {
            line = Console.ReadLine().Trim().Split(' ');
            var s = int.Parse(line[0]);
            var t = int.Parse(line[1]);
            d[s].to.Add(t);
            d[t].from.Add(s);
        }
        Console.WriteLine(checkCycle(d, n) ? 1 : 0);
    }
    public static bool checkCycle(Dictionary<int, P> d, int n)
    {
        var q = new Queue<int>();
        var check = new int[n];
        for (int i = 0; i < n; i++) q.Enqueue(i);
        while (q.Count() > 0)
        {
            var w = q.Dequeue();
            if (d[w].from.Count == 0)
            {
                foreach (var x in d[w].to) d[x].from.Remove(w);
            }
            else
            {
                check[w]++;
                if (check[w] == 5) return true;
                else q.Enqueue(w);
            }
        }
        return false;
    }
}