Skip to content

Commit 6b15c8f

Browse files
authored
Merge pull request neetcode-gh#1996 from AkifhanIlgaz/1443
Create: 1443-minimum-time-to-collect-all-apples-in-a-tree.rs
2 parents 0018844 + 1ba11bc commit 6b15c8f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy