Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1996 from AkifhanIlgaz/1443
Browse files Browse the repository at this point in the history
Create: 1443-minimum-time-to-collect-all-apples-in-a-tree.rs
  • Loading branch information
tahsintunan authored Jan 12, 2023
2 parents 0018844 + 1ba11bc commit 6b15c8f
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions rust/1443-minimum-time-to-collect-all-apples-in-a-tree.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use std::collections::HashMap;

impl Solution {
pub fn min_time(n: i32, edges: Vec<Vec<i32>>, has_apple: Vec<bool>) -> i32 {
let mut adj = HashMap::new();

for edge in edges {
let (parent, child) = (edge[0], edge[1]);
adj.entry(parent).or_insert(vec![]).push(child);
adj.entry(child).or_insert(vec![]).push(parent);
}

fn dfs(
current: i32,
parent: i32,
adj: &HashMap<i32, Vec<i32>>,
has_apple: &Vec<bool>,
) -> i32 {
let mut time = 0;

if let Some(children) = adj.get(&current) {
for child in children {
if *child == parent {
continue;
}
let child_time = dfs(*child, current, &adj, &has_apple);

if child_time.is_positive() || has_apple[*child as usize] {
time += 2 + child_time;
}
}
}

time
}

dfs(0, -1, &adj, &has_apple)
}
}

0 comments on commit 6b15c8f

Please sign in to comment.