---
# System prepended metadata

title: 2368. Reachable Nodes With Restrictions
tags: [Leetcode, BFS, DFS, Medium]

---

# 2368. Reachable Nodes With Restrictions
###### tags: `Leetcode` `Medium` `BFS` `DFS`
Link: https://leetcode.com/problems/reachable-nodes-with-restrictions/description/
## 思路
BFS
碰到restricted node就不会往下走了
可以把visited set和装restricted node的set和在一起
## Code
```java=
class Solution {
    public int reachableNodes(int n, int[][] edges, int[] restricted) {
        Set<Integer> set = new HashSet<>();
        for(int r:restricted) set.add(r);
        List<List<Integer>> graph = new ArrayList<>();
        for(int i=0; i<n; i++) graph.add(new ArrayList<>());
        for(int[] edge:edges){
            graph.get(edge[0]).add(edge[1]);
            graph.get(edge[1]).add(edge[0]);
        }       
        int cnt = 0;
        Queue<Integer> q = new LinkedList<>();
        q.add(0);
        set.add(cnt);
        while(!q.isEmpty()){
            int curr = q.poll();
            cnt++;
            for(int next:graph.get(curr)){
                if(set.contains(next)) continue;
                set.add(next);
                q.add(next);
            }
        }
        return cnt;
    }
}
```