why is this incorrect?


  • 0
    T

    Can someone please point out what I am missing here?

    public class Solution {
        public int countComponents(int n, int[][] edges) {
            if(n<1 || edges == null || edges.length == 0) return 0;
            Map<Integer, List<Integer>> map = new HashMap<>();
            for(int i = 0;i<edges.length;i++){
                int key = edges[i][0];
                int val = edges[i][1];
                if(!map.containsKey(key)) map.put(key, new ArrayList<Integer>());
                map.get(key).add(val);
            }
            Set<Integer> set = new HashSet<>();
            int count = 0;
            for(int key: map.keySet()){
                if(!set.contains(key)){
                    count++;
                    dfs(key, set, map);
                }    
            }
            return count;
        }
        
        private void dfs(int key, Set<Integer> set, Map<Integer, List<Integer>> map){
            if(!map.containsKey(key)) return;
            if(!set.add(key)) return;
            for(int k: map.get(key)){
                dfs(k, set, map);
            }
        }
    }
    

    Failing test case is

    Input:
    4
    [[2,3],[1,2],[1,3]]
    Output:
    1
    Expected:
    2
    

    Shouldn't the output be 1 ? In a way that
    1
    | \
    2 -- 3


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.