Tried many test cases available on the internet, worked for them, but not working for submission.
What am i Doing wrong in this?
public class Main
{
public static void main(String [] args)
{
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int m = scn.nextInt();
//graph
HashMap <Integer, HashSet <Integer> > graph = new HashMap <> ();
for(int i = 1; i<=m; i++)
{
int x = scn.nextInt();
int y = scn.nextInt();
if(!graph.containsKey(x))
graph.put(x, new HashSet <> ());
if(!graph.containsKey(y))
graph.put(y, new HashSet <> ());
if(x < y)
graph.get(x).add(y);
else
graph.get(y).add(x);
}
System.out.println(beautifulVertices(graph));
}
public static int beautifulVertices(HashMap <Integer, HashSet<Integer>>graph)
{
int count = 0;
HashMap <Integer,Boolean> visited = new HashMap <> ();
for(int key : graph.keySet())
{
if(visited.containsKey(key))
continue;
Queue <Integer> q = new LinkedList <> ();
q.add(key);
while(!q.isEmpty())
{
int rv = q.remove();
if(visited.containsKey(rv))
continue;
visited.put(rv,true);
for(int nbr : graph.get(rv))
{
if(visited.containsKey(nbr))
continue;
if(graph.get(nbr).size() > graph.get(key).size())
count++;
q.add(nbr);
}
}
}
return count;
}
}