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: Runtime Error)

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Vector;

class problemB {
  void solve(){

    Scanner scan = new Scanner(System.in);
    int v = scan.nextInt();
    int e = scan.nextInt();

    int[][] g = new int[v][v];
    int[] visit = new int[v];
    int cycle = 0;


    for(int i=0 ; i<v ; i++){
      visit[i] = 0;
      for(int j=0 ; j<v ; j++){
        g[i][j] = -1;
      }
    }

    for(int i=0 ; i<e ; i++){
      int s = scan.nextInt();
      int t = scan.nextInt();
      if(s!=t) g[s][t] = 1;
    }

    for(int i=0 ; i<e ; i++){
      for(int j=0 ; j<e ; j++){
        if(g[i][j]==1) cycle = visitNode(j, g, visit);
      }
    }

    System.out.println(cycle);

  }//---end of solve---

  int visitNode(int s, int[][] g, int[] visit){
    visit[s] = 1;
    for(int i=0 ; i<g[s].length ; i++){
      if(g[s][i] == 1){
        if(visit[s] < 0) visitNode(i, g, visit);
        else{
         return 1;
        }
      }
    }
    return 0;
  }//----end of visitNode----
}//----end of class----

public class Main {
  public static void main(String args[]){
    new problemB().solve();
  }
}