2368. Reachable Nodes With Restrictions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public int reachableNodes(int n, int[][] edges, int[] restricted) {
Map<Integer, List<Integer>> nodeToNodeListMap = new HashMap<>();
for (int i = 0; i < n; i++) {
nodeToNodeListMap.put(i, new ArrayList<>());
}
for (int[] edge : edges) {
int nodeA = edge[0], nodeB = edge[1];
nodeToNodeListMap.get(nodeA).add(nodeB);
nodeToNodeListMap.get(nodeB).add(nodeA);
}

int reachableNodes = 0;

Set<Integer> visitedSet = new HashSet<>();
for (int r : restricted) {
visitedSet.add(r);
}
Queue<Integer> queue = new LinkedList<>();
queue.add(0);

while (!queue.isEmpty()) {
int node = queue.poll();
visitedSet.add(node);
reachableNodes++;

for (int neighbor : nodeToNodeListMap.get(node)) {
if (visitedSet.contains(neighbor)) {
continue;
}

queue.offer(neighbor);
}
}

return reachableNodes;
}
}

References

2368. Reachable Nodes With Restrictions