---
# System prepended metadata

title: 2876. Count Visited Nodes in a Directed Graph

---

 2876. Count Visited Nodes in a Directed Graph

``` java=

1. 只要能夠被分在同ㄧ個 cycle 就是就是相同的 拜訪個數
2. 如果該點已經更新過拜訪的個數, 就加上去已拜訪的個數

class Solution {
    public int[] countVisitedNodes(List<Integer> edges) {
        int n = edges.size();
        boolean visited [] = new boolean [n];
       
        int res [] = new int [n];
        Arrays.fill(res, -1);
        
        for(int i = 0; i < n; i++){
            if(!visited [i]){
                Set<Integer> set = new HashSet<>();
                 Map<Integer, Set<Integer>> map = new HashMap<>();
                int ret = dfs(edges, i, visited, set, res);
                //System.out.println(i +":" + ret);
                map.put(set.size(), set);
                for(Map.Entry<Integer, Set<Integer>> m : map.entrySet()){
                    for(int mp : m.getValue()){

                         res [mp] = m.getKey() + (ret != -1 ? ret : 0) ;
                    }
                }
            }
            
        }
        
    
        return res;
        
        
    }
    
    
    private int dfs(List<Integer> edges, int u, boolean visited [], Set<Integer> set, int res []){
        if(visited[u]){
            return res[u];
        }
        
        visited[u] = true;
        
        set.add(u);
        
        int v = edges.get(u);
        return dfs(edges, v, visited, set, res);
       
    }
}
```