Reachable Nodes With Restrictions Problem
#2368
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2368.
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] = [a_i, b_i] indicates that there is an edge between nodes a_i and b_i 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 0 without visiting a restricted node.
Note that node 0 will not be a restricted node.
Example 1:

Input: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]
Output: 4
Explanation: 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.
Example 2:

Input: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]
Output: 3
Explanation: 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.
Constraints:
2 <= n <= 10^5edges.length == n - 1edges[i].length == 20 <= a_i, b_i < na_i != b_iedgesrepresents a valid tree.1 <= restricted.length < n1 <= restricted[i] < n- All the values of
restrictedare unique.
Solution
Approach: DFS From Node 0
Build the adjacency lists of the tree and mark the restricted nodes as already visited, so a search never enters them. Then run a depth-first search from node 0 and count the nodes it reaches.
Complexity: O(n) time and O(n) space.
from collections import defaultdict
class Solution:
def reachableNodes(
self, n: int, edges: List[List[int]], restricted: List[int]
) -> int:
def dfs(i: int) -> int:
vis.add(i)
return 1 + sum(j not in vis and dfs(j) for j in g[i])
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
vis = set(restricted)
return dfs(0)