We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
publicstaticintjourneyToMoon(intn,List<List<Integer>>astronaut){// Write your code hereMap<Integer,List<Integer>>adj=buildAdjList(n,astronaut);Set<Integer>visited=newHashSet<>();Set<Set<Integer>>countries=newHashSet<>();for(inti=0;i<n;i++){if(!visited.contains(i)){Set<Integer>astronautInCountry=newHashSet<>();dfsVisit(adj,i,visited,astronautInCountry);countries.add(astronautInCountry);}}longresult=0;for(Set<Integer>country:countries){// If choose 1st atronaut from country, there are (n - country.size()) astronaut to choose 2nd.result+=(country.size()*(n-country.size()));}return(int)(result/2);}privatestaticvoiddfsVisit(finalMap<Integer,List<Integer>>adj,intnode,Set<Integer>visited,Set<Integer>astronautInCountry){visited.add(node);astronautInCountry.add(node);for(intneighbor:adj.get(node)){if(!visited.contains(neighbor)){dfsVisit(adj,neighbor,visited,astronautInCountry);}}}privatestaticMap<Integer,List<Integer>>buildAdjList(intn,List<List<Integer>>astronaut){Map<Integer,List<Integer>>adj=newHashMap<>();for(inti=0;i<n;i++){adj.put(i,newArrayList<>());}for(List<Integer>edge:astronaut){adj.get(edge.get(0)).add(edge.get(1));adj.get(edge.get(1)).add(edge.get(0));}returnadj;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Journey to the Moon
You are viewing a single comment's thread. Return to all comments →
Test case 11 does not pass. All others pass.
Solution using DFS.