Graphical Park
Alex lives in a park that forms a tree graph.
Node 1 is Alex's home, Some nodes contain cats, Leaf nodes represent restaurants.
Alex wants to go from his home to a restaurant. However If the path contains more than m consecutive cats, he refuses to go.
Cats array is represented by 0-indexed binary array of length N (cats[i] corresponds to Node i+1).
Edges array is n-1 undirected pairs forming a valid, connected tree.
Your task is to Count how many leaf nodes (restaurants) are reachable such that the path from node 1 to that leaf has: ≤ m consecutive cat nodes
Example 1:
Input : n = 4, m = 1 ,cats = [1,1,0,0] , edges = [[1,2], [1,3], [1,4]]
Output : 2
Explanation:
Paths:
1 → 2 1 → 3 1 → 4
Check consecutive cats:
1 → 2 → cats = [1,1] → 2 consecutive > m → invalid 1 → 3 → cats = [1,0] → valid 1 → 4 → cats = [1,0] → valid
Valid restaurants: 3,4
Answer: 2
Example 2:
Input : n = 7, m = 1, cats = [1,0,1,1,0,0,0] ,edges = [[1,2], [1,3], [2,4], [2,5], [3,6], [3,7]]
Output : 2
Explanation :
Leaf nodes: 4,5,6,7
Paths:
1→2→4 : cats = [1,0,1] → valid 1→2→5 : cats = [1,0,0] → valid 1→3→6 : cats = [1,1,0] → 2 consecutive → invalid 1→3→7 : cats = [1,1,0] → invalid
Valid restaurants: 4,5
Answer: 2
Now Your Turn!
Pick the correct output for the given inputInput : n = 4, m = 1, cats = [1,1,1,0] , edges = [[1,2], [2,3], [3,4]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 2 ≤ n ≤ 100000
- 1 ≤ m ≤ n
- cats[i] ∈ {0,1}
- edges = n-1
- Graph is a tree