Skip to content

Commit a19ff6c

Browse files
authored
Create Reachable Nodes With Restrictions.java
1 parent 4d9c778 commit a19ff6c

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public int reachableNodes(int n, int[][] edges, int[] restricted) {
3+
Map<Integer, List<Integer>> graph = new HashMap<>();
4+
for (int[] edge : edges) {
5+
graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]);
6+
graph.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]);
7+
}
8+
Set<Integer> restrictedSet = Arrays.stream(restricted).boxed().collect(Collectors.toSet());
9+
Set<Integer> visited = new HashSet<>();
10+
Queue<Integer> queue = new LinkedList<>();
11+
queue.add(0);
12+
visited.add(0);
13+
while (!queue.isEmpty()) {
14+
int size = queue.size();
15+
while (size-- > 0) {
16+
int node = queue.remove();
17+
for (Integer neighbor : graph.getOrDefault(node, new ArrayList<>())) {
18+
if (restrictedSet.contains(neighbor) || visited.contains(neighbor)) {
19+
continue;
20+
}
21+
queue.add(neighbor);
22+
visited.add(neighbor);
23+
}
24+
}
25+
}
26+
return visited.size();
27+
}
28+
}

0 commit comments

Comments
 (0)