Advertisement
nikunjsoni

1443

Apr 29th, 2021
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int res = 0;
  4.     int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) {
  5.         vector<vector<int>> graph(n);
  6.         for(auto edge: edges){
  7.             graph[edge[0]].push_back(edge[1]);
  8.             graph[edge[1]].push_back(edge[0]);
  9.         }
  10.         vector<bool> vis(n, false);
  11.         dfs(0, graph, hasApple, vis);
  12.         return res;
  13.     }
  14.    
  15.     int dfs(int node, vector<vector<int>>& graph, vector<bool>& hasApple, vector<bool>& vis){
  16.         int exists = 0;
  17.         vis[node] = true;
  18.         for(auto child: graph[node])
  19.             if(!vis[child])
  20.                 exists += dfs(child, graph, hasApple, vis);
  21.        
  22.         res += exists*2;
  23.         if(hasApple[node] || exists)
  24.             return 1;
  25.         return 0;
  26.     }
  27. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement