Below is the code for Journey to Moon Problem from hackerrank
its failing 12/16 test cases
Please help where am i going wrong ?
public class Solution {
// Complete the journeyToMoon function below.
static int journeyToMoon(int n, int[][] astronaut) {
// Graph g = new Graph(n);
// List<List<Integer>> adjList = g.addEdge(astronaut);
int vertices;
List<List<Integer>> adjList=new ArrayList<>();
for(int i=0;i<n;i++)
{
adjList.add(i,new ArrayList<Integer>());
}
for(int[] edge : astronaut)
{
adjList.get(edge[0]).add(edge[1]);
adjList.get(edge[1]).add(edge[0]);
}
boolean visited[] = new boolean[n+1];
//visited[0] = true;
int[] components = new int[100];
int component=0;
int count =0;
for(int i=0;i<n;i++)
{
if(!visited[i])
{
count = DFS_HELPER(i,visited,0,adjList);
//System.out.println("count "+count);
components[component]=count;
component++;
}
}
//System.out.println("component "+component);
int total_members =0;
int dup = 0;
for(int i=0;i<components.length;i++)
{
total_members = total_members+components[i];
dup = dup + nCr(components[i],2);
}
//System.out.println("total_members "+total_members);
return nCr(total_members,2)-dup;
}
static int DFS_HELPER(int src,boolean[] visited,int count,List<List<Integer>>adjList)
{
visited[src]=true;
for(int neighbour : adjList.get(src))
{
if(!visited[neighbour])
{
count++;
DFS_HELPER(neighbour,visited,count,adjList);
}
}
return count+1;
}
static int nCr(int n, int r)
{
return fact(n) / (fact(r) *
fact(n - r));
}
// Returns factorial of n
static int fact(int n)
{
int res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
//BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] np = scanner.nextLine().split(" ");
int n = Integer.parseInt(np[0]);
int p = Integer.parseInt(np[1]);
int[][] astronaut = new int[p][2];
for (int i = 0; i < p; i++) {
String[] astronautRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int j = 0; j < 2; j++) {
int astronautItem = Integer.parseInt(astronautRowItems[j]);
astronaut[i][j] = astronautItem;
}
}
int result = journeyToMoon(n, astronaut);
System.out.print(result);
// bufferedWriter.write(String.valueOf(result));
// bufferedWriter.newLine();
//
// bufferedWriter.close();
scanner.close();
}