2015-01-04 46 views
-4
enter code here 
import java.io.*; 
import java.util.*; 
import java.text.*; 
import java.math.*; 
import java.util.regex.*; 

public class Solution 
{ 
    static boolean visited[]; 
    static int vertices; 
    static boolean tree[][]; 

    public static void main(String[] args) 
    { 
     /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 
     Scanner sc=new Scanner(System.in); 

     vertices=sc.nextInt(); 
     int edges=sc.nextInt(); 

     visited=new boolean[vertices+1]; 


     boolean tree[][]=new boolean[vertices+1][vertices+1]; 
     for (int k=0;k<vertices+1 ;k++) 
     { 
      for (int j=0;j<vertices+1 ;j++) 
      { 
       tree[k][j]=false; 
      } 

     } 

     int count[]=new int[vertices+1]; 
     //Arrays.fill(count,1); 

     for(int i=0;i<edges;i++) 
      { 
      int u=sc.nextInt(); 
      int v=sc.nextInt(); 

      tree[v][u]=true; 



     } 

     for (int i=0;i<vertices+1 ;i++) 
     { 
      count[i]=bfs(i) + 1;    //getting error at this line 

     } 
     int finalcount=0; 
     for (int i=0;i<vertices+1 ;i++) 
     { 
      if (count[i]%2==0) 
      { 
       finalcount++; 

      } 

     } 

     System.out.println(finalcount); 


    } 

    public static int bfs(int node) 
     { 
     Queue<Integer> q=new LinkedList<Integer>(); 
     for(int i=0;i<vertices+1;i++) 
      { 
      visited[i]=false; 
     } 
     visited[0]=true; 
     int counter=0; 
     q.add(node); 
     while(!q.isEmpty()) 
     { 
     int nextNode;    // Next node to visit 
     int i; 

     nextNode = Integer.valueOf(q.remove()); 

     if (! visited[nextNode]) 
     { 
      visited[nextNode] = true; //mark visited 


      for (i = 0; i < vertices+1; i++) 
      { 
       if (tree[nextNode][i] && ! visited[i]) //getting error at this line too 
       { 
        q.add(i); 
        counter++; 
       } 
      } 
     } 
     } 

     return counter; 
    } 
} 





/* 

10 9 
2 1 
3 1 
4 3 
5 2 
6 1 
7 2 
8 6 
9 8 
10 8 
ans:2 


20 19 
2 1 
3 1 
4 3 
5 2 
6 5 
7 1 
8 1 
9 2 
10 7 
11 10 
12 3 
13 7 
14 8 
15 12 
16 6 
17 6 
18 10 
19 1 
20 8 
ans:4 



*/ 

我得到了nullpointerexception。我已经评论了错误发生的地方。请帮忙!为什么我在这段代码中获得nullpointerexception?

这是hackerrrank甚至树问题的解决方案...我知道逻辑,但得到这个错误。

+1

在这里发表您的堆栈跟踪。哪条线路导致问题? –

回答

3

这是你的问题:

public class Solution 
{ 
    ... 
    static boolean tree[][]; 
    ... 
    public static void main(String[] args) 
    { 
     ... 
     boolean tree[][]=new boolean[vertices+1][vertices+1]; 
     ... 

初始化本地tree阵列,而不是你的静态tree成员,这仍然是空的。

将其更改为:

public class Solution 
{ 
    ... 
    static boolean tree[][]; 
    ... 
    public static void main(String[] args) 
    { 
     ... 
     tree = new boolean[vertices+1][vertices+1]; 
     ... 
+0

谢谢。刚刚意识到它。 – Kashyap

相关问题