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

def check(i)
#  puts "i=#{i}"
#  puts "gs[i]=#{$gs[i]}"
  $gs[i][1] = 1
  $gs[i][0].each{|temp|
#    puts "next_color:#{$gs[temp][1]}"
    if $gs[temp][1] == 1
#      puts "next:#{$gs[temp][1]}"
      $cflag = true
    elsif $gs[temp][1] == 0
      check(temp)
    end
  }
  $gs[i][1] = -1
end

$gs = []
$cflag = false
v,e = gets.split.map(&:to_i)
v.times{
  $gs << [[],0]
}
e.times do
  s,t = gets.split.map(&:to_i)
  $gs[s][0] << t
end
$gs.each_with_index{|g,i|
  if g[1] == 0
    check(i)
  end
}
if $cflag
  puts "1"
else
  puts "0"
end