Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://practice.geeksforgeeks.org/problems/f7bfa137576243795abb0595962d61b632bbad21/1
- Given N nodes of a tree and a list of edges. Find the minimum number of nodes to be selected to light up all the edges of the tree.
- An edge lights up when at least one node at the end of the edge is selected.
- Example 1:
- Input:
- N = 6
- edges[] = {(1,2), (1,3), (2,4), (3,5), (3,6)}
- Output: 2
- Explanation: Selecting nodes 2 and 3 lights
- up all the edges.
- Example 2:
- Input:
- N = 3
- arr[] = {(1,2), (1,3)}
- Output: 1
- Explanation: Selecting Node 1
- lights up all the edges.
- ---------------------------------------------------------------------------------------------------------------------------------------
- class Solution{
- private:
- vector<vector<int>> adj;
- public:
- int res=0;
- bool helper(int src, int par){
- bool SELECT_ROOT=false;
- for(auto nei: adj[src]){
- if(nei!=par){
- bool isChildSelected=helper(nei,src);
- if(isChildSelected==false){
- SELECT_ROOT=true; // WE CANNOT BREAK OUT YET, WE NEED TO CHECK ALL CHILDREN BEFORE EXITING
- }
- }
- }
- if(SELECT_ROOT==true){
- res++;
- }
- return SELECT_ROOT;
- }
- int countVertex(int N, vector<vector<int>>edges){
- adj.resize(N+1);
- res=0;
- for(auto edge: edges){
- adj[edge[0]].push_back(edge[1]);
- adj[edge[1]].push_back(edge[0]);
- }
- helper(1,-1);
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment