Leetcode 2368 Reachable Nodes With Restrictions Solution in Java | Hindi Coding Community

0

 



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 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 <= 105
  • 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 the values of restricted are unique.

Java Code :



class Solution {
public int reachableNodes(int n, int[][] e, int[] r) {
List<List<Integer>> nm=new ArrayList<>();
for(int i=0;i<e.length+1;i++)
{
nm.add(new ArrayList<>());
}
for(int i=0;i<e.length;i++)
{
nm.get(e[i][0]).add(e[i][1]);
nm.get(e[i][1]).add(e[i][0]);
}
int c=0;
Queue<Integer> kk=new LinkedList<>();
kk.offer(0);
Set<Integer> k=new HashSet<>();
k.add(0);
for(int i:r)
{
k.add(i);
}
while(!kk.isEmpty())
{
int p=kk.size();
while(p>0)
{
c++;
int f=kk.poll();
for(int i:nm.get(f))
{
if(!k.contains(i))
{
kk.offer(i);
k.add(i);
}
}
p--;
}
}
return c;
}
}


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !