[LeetCode] Minimum Time to Collect All Apples in a Tree

1443. Minimum Time to Collect All Apples in a Tree

Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.

The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
vector<vector<int>> adj;
int dfs(int u, int p, vector<bool>& A) {
int res = 0;

for(auto& v : adj[u])
if(v != p)
res += dfs(v, u, A);
return res + (res or A[u] ? 2 : 0);
}
public:
int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) {
adj = vector<vector<int>>(n);
for(auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
return max(0, dfs(0, -1, hasApple) - 2);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/21/PS/LeetCode/minimum-time-to-collect-all-apples-in-a-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.