• + 1 comment

    Test case 11 does not pass. All others pass.

    Solution using DFS.

    public static int journeyToMoon(int n, List<List<Integer>> astronaut) {
            // Write your code here
            Map<Integer, List<Integer>> adj = buildAdjList(n, astronaut);
    
            Set<Integer> visited = new HashSet<>();
            Set<Set<Integer>> countries = new HashSet<>();
            for (int i=0;i<n;i++) {
                if (!visited.contains(i)) {
                    Set<Integer> astronautInCountry = new HashSet<>();
                    
                    dfsVisit(adj, i, visited, astronautInCountry);
                    
                    countries.add(astronautInCountry);
                }
            }
            long result = 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);
        }
        
        private static void dfsVisit(final Map<Integer, List<Integer>> adj, int node, Set<Integer> visited, Set<Integer> astronautInCountry) {
            visited.add(node);
            astronautInCountry.add(node);
            
            for (int neighbor : adj.get(node)) {
                if (!visited.contains(neighbor)) {
                    dfsVisit(adj, neighbor, visited, astronautInCountry);
                }
            }
        }
        
        private static Map<Integer, List<Integer>> buildAdjList(int n, List<List<Integer>> astronaut) {
            Map<Integer, List<Integer>> adj = new HashMap<>();
            
            for (int i=0; i<n; i++) {
                adj.put(i, new ArrayList<>());
            }
            for (List<Integer> edge : astronaut ) {
                adj.get(edge.get(0)).add(edge.get(1));
                adj.get(edge.get(1)).add(edge.get(0));
            }
            
            return adj;
        }