Leetcode 2368: Reachable Nodes With Restrictions

grid47
grid47
Exploring patterns and algorithms
Mar 15, 2024 6 min read

You are given a tree with n nodes and n - 1 edges, where nodes are labeled from 0 to n - 1. Additionally, a list of restricted nodes is provided. Your goal is to determine the maximum number of nodes that can be visited starting from node 0, without passing through any restricted node. Node 0 itself is not restricted.
Problem
Approach
Steps
Complexity
Input: You are given the number of nodes n, a list of edges describing the tree, and a list of restricted nodes.
Example: n = 6, edges = [[0,1], [0,2], [2,3], [3,4], [4,5]], restricted = [2, 5]
Constraints:
• 2 <= n <= 10^5
• edges.length == n - 1
• edges[i].length == 2
• 0 <= ai, bi < n
• ai != bi
• edges represents a valid tree
• 1 <= restricted.length < n
• 1 <= restricted[i] < n
• All restricted nodes are unique
Output: Return the maximum number of nodes that can be reached from node 0 without passing through any restricted node.
Example: Output: 3
Constraints:
Goal: The goal is to find the maximum reachable nodes starting from node 0 while avoiding restricted nodes.
Steps:
• Construct an adjacency list from the given edges.
• Mark all restricted nodes as visited.
• Perform a Depth First Search (DFS) or Breadth First Search (BFS) starting from node 0, skipping any restricted nodes.
• Count the number of nodes visited during the traversal.
Goal: The tree structure guarantees a valid configuration of nodes and edges. The restricted nodes list contains unique values, and node 0 is not restricted.
Steps:
• n is between 2 and 10^5
• edges form a valid tree
• restricted nodes are unique and non-empty
Assumptions:
• Node 0 will not be restricted.
• The given tree is valid, and each node can only have a unique set of neighbors.
Input: Input: n = 6, edges = [[0,1], [0,2], [2,3], [3,4], [4,5]], restricted = [2, 5]
Explanation: In this example, the nodes that can be visited from node 0 are 1, 3, and 4. Node 2 and node 5 are restricted, so they cannot be visited. Hence, the output is 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus