Can please anyone help me in finding my mistake? I have tried 3 days to solve this problems but still am getting runtime errors at testcase 6. I am using BFS search using Queue.
I am storing 1 in those positions of 2D array where there is an edge between nodes. Then I am adding node 1 to the queue and traversing its neighbouring nodes and adding them to queue and making visited[node][node] =1. Is there mistake in my implementation of the bfs algorithm.Kindly help me!!!
import java.io.*;
import java.lang.*;
import java.util.*;
class PT07Y
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int i,j,k;boolean flag= false;
int n = Integer.parseInt(st.nextToken());
int e = Integer.parseInt(st.nextToken());
int small=0;
int grid[][] = new int[n+1][n+1];
for(k=0;k<e;k++)
{ if(!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
i = Integer.parseInt(st.nextToken());
j =Integer.parseInt(st.nextToken());
if(i<j)
{grid[i][j] = 1;
}
else
{grid[j][i]=1;
}
}
if(e!=n-1)
{
System.out.println("NO");
System.exit(1);
}
int visited[][] = new int[n+1][n+1];
Queue<Node> myQueue = new LinkedList<Node>();
myQueue.add(new Node(1));
visited[1][1]=1;int count=1;
while(myQueue.isEmpty()!=true)
{
Node current = myQueue.remove();
j=current.data;
for(k=1;k<=n;k++)
{
if(grid[j][k]==1)
{
if(visited[k][k]!=1)
{
myQueue.add(new Node(k));
visited[k][k]=1;
count++;
}
else
{
if(j<k){
System.out.println("NO");
flag=true;
break;
}
}
}
}
if(flag==true)break;
}
if(count<n)
{System.out.println("NO");}
else if(flag==false)System.out.println("YES");
}
}
class Node
{
int data;
public Node(int d)
{
this.data = d;
}
}