From 1ba11bc269047e33aa5b738a7672f8364a9d18ff Mon Sep 17 00:00:00 2001 From: AkifhanIlgaz Date: Wed, 11 Jan 2023 16:15:01 +0300 Subject: [PATCH] Create: 1443-minimum-time-to-collect-all-apples-in-a-tree.rs --- ...um-time-to-collect-all-apples-in-a-tree.rs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 rust/1443-minimum-time-to-collect-all-apples-in-a-tree.rs diff --git a/rust/1443-minimum-time-to-collect-all-apples-in-a-tree.rs b/rust/1443-minimum-time-to-collect-all-apples-in-a-tree.rs new file mode 100644 index 000000000..42ab64ed6 --- /dev/null +++ b/rust/1443-minimum-time-to-collect-all-apples-in-a-tree.rs @@ -0,0 +1,39 @@ +use std::collections::HashMap; + +impl Solution { + pub fn min_time(n: i32, edges: Vec>, has_apple: Vec) -> 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>, + has_apple: &Vec, + ) -> i32 { + let mut time = 0; + + if let Some(children) = adj.get(¤t) { + 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) + } +} \ No newline at end of file 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