There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array restricted which represents restricted nodes.
Return _the maximum number of nodes you can reach from node _0without visiting a restricted node.
graph TD
classDef reachable fill:#51ff51,stroke:#2b8fb8,stroke-width:2px;
classDef restricted fill:#ffe6e6,stroke:#d9534f,stroke-width:1.5px;
0(0):::reachable
1(1):::reachable
2(2):::reachable
3(3):::reachable
4(4):::restricted
5(5):::restricted
6(6)
0 --- 1
1 --- 2
1 --- 3
0 --- 4
0 --- 5
5 --- 6
%% reachable: 0,1,2,3 (4 and 5 are restricted so their branches are blocked)
1
2
3
4
Input: n =7, edges =[[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted =[4,5]Output: 4Explanation: The diagram above shows the tree.We have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.
Input: n =7, edges =[[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted =[4,2,1]Output: 3Explanation: The diagram above shows the tree.We have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.
We are given a tree and a set of restricted nodes. We need to count how many nodes are reachable from node 0 without visiting any restricted node. Since the graph is a tree (acyclic, connected), we can use BFS or DFS to traverse from node 0, skipping restricted nodes.
classSolution {
funreachableNodes(n: Int, edges: Array<IntArray>, restricted: IntArray): Int {
val adj = Array(n) { mutableListOf<Int>() }
for (e in edges) {
adj[e[0]].add(e[1])
adj[e[1]].add(e[0])
}
val rest = restricted.toHashSet()
val vis = BooleanArray(n)
val q = ArrayDeque<Int>()
q.add(0)
vis[0] = truevar cnt = 0while (q.isNotEmpty()) {
val u = q.removeFirst()
cnt++for (v in adj[u]) {
if (!vis[v] && v !in rest) {
vis[v] = true q.add(v)
}
}
}
return cnt
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from collections import deque, defaultdict
classSolution:
defreachableNodes(self, n: int, edges: list[list[int]], restricted: list[int]) -> int:
adj = defaultdict(list)
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
rest = set(restricted)
vis = {0}
q = deque([0])
cnt =0while q:
u = q.popleft()
cnt +=1for v in adj[u]:
if v notin vis and v notin rest:
vis.add(v)
q.append(v)
return cnt