Skip to content

Commit 1ba11bc

Browse files
committed
Create: 1443-minimum-time-to-collect-all-apples-in-a-tree.rs
1 parent ee7a3bc commit 1ba11bc

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
use std::collections::HashMap;
2+
3+
impl Solution {
4+
pub fn min_time(n: i32, edges: Vec<Vec<i32>>, has_apple: Vec<bool>) -> i32 {
5+
let mut adj = HashMap::new();
6+
7+
for edge in edges {
8+
let (parent, child) = (edge[0], edge[1]);
9+
adj.entry(parent).or_insert(vec![]).push(child);
10+
adj.entry(child).or_insert(vec![]).push(parent);
11+
}
12+
13+
fn dfs(
14+
current: i32,
15+
parent: i32,
16+
adj: &HashMap<i32, Vec<i32>>,
17+
has_apple: &Vec<bool>,
18+
) -> i32 {
19+
let mut time = 0;
20+
21+
if let Some(children) = adj.get(&current) {
22+
for child in children {
23+
if *child == parent {
24+
continue;
25+
}
26+
let child_time = dfs(*child, current, &adj, &has_apple);
27+
28+
if child_time.is_positive() || has_apple[*child as usize] {
29+
time += 2 + child_time;
30+
}
31+
}
32+
}
33+
34+
time
35+
}
36+
37+
dfs(0, -1, &adj, &has_apple)
38+
}
39+
}

0 commit comments

Comments
 (0)