Reachable Nodes With Restrictions - Problem
Imagine you're exploring a connected network of locations, but some areas are off-limits! You have an undirected tree with n nodes labeled from 0 to n - 1, connected by exactly n - 1 edges.
You're given:
- A 2D array
edgeswhereedges[i] = [a_i, b_i]represents a connection between nodesa_iandb_i - An array
restrictedcontaining nodes you cannot visit
Goal: Starting from node 0 (which is never restricted), find the maximum number of nodes you can reach without passing through any restricted nodes.
Think of it as exploring a city where certain intersections are blocked - you want to see how much of the city you can still explore!
Input & Output
example_1.py โ Basic Tree
$
Input:
n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]
โบ
Output:
4
๐ก Note:
Starting from node 0, we can reach nodes 1, 2, and 3. We cannot reach nodes 4, 5, or 6 because nodes 4 and 5 are restricted, blocking the path to node 6.
example_2.py โ Single Restriction
$
Input:
n = 4, edges = [[0,1],[1,2],[2,3]], restricted = [2]
โบ
Output:
2
๐ก Note:
From node 0, we can only reach node 1. Node 2 is restricted, which also blocks access to node 3.
example_3.py โ No Restrictions
$
Input:
n = 5, edges = [[0,1],[0,2],[1,3],[1,4]], restricted = []
โบ
Output:
5
๐ก Note:
With no restrictions, we can reach all nodes from node 0. The tree is fully traversable.
Constraints
- 2 โค n โค 105
- edges.length == n - 1
- edges[i].length == 2
- 0 โค ai, bi < n
- ai โ bi
- edges represents a valid tree
- 1 โค restricted.length < n
- 0 โค restricted[i] < n
- All the values of restricted are unique
- restricted does not contain 0
Visualization
Tap to expand
Understanding the Visualization
1
Mark Blocked Areas
Convert restricted nodes array to hash set for instant lookup
2
Start Exploration
Begin DFS from node 0 (the depot/starting point)
3
Check Before Moving
For each neighbor, check if it's blocked using O(1) hash lookup
4
Count Reachable
Accumulate count of all nodes visited during the traversal
Key Takeaway
๐ฏ Key Insight: Use DFS with hash set for O(1) restriction checks - single traversal gives O(n) optimal solution!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code