20240302 Finished

This commit is contained in:
jackfiled 2024-03-02 10:13:37 +08:00
parent 8bc2e0d347
commit 0e1b35b21e
2 changed files with 65 additions and 1 deletions

View File

@ -60,4 +60,5 @@ mod p889_construct_binary_tree_from_preorder_and_postorder_traversal;
mod p2867_count_valid_paths_in_a_tree; mod p2867_count_valid_paths_in_a_tree;
mod p2673_make_costs_of_paths_equal_in_a_binary_tree; mod p2673_make_costs_of_paths_equal_in_a_binary_tree;
mod p2581_count_number_of_possible_root_nodes; mod p2581_count_number_of_possible_root_nodes;
mod p2369_check_if_there_is_a_valid_partition_for_the_array; mod p2369_check_if_there_is_a_valid_partition_for_the_array;
mod p2368_reachable_nodes_with_restrictions;

View File

@ -0,0 +1,63 @@
/**
* [2368] Reachable Nodes With Restrictions
*/
pub struct Solution {}
// submission codes start here
use std::collections::VecDeque;
use std::collections::HashSet;
impl Solution {
pub fn reachable_nodes(n: i32, edges: Vec<Vec<i32>>, restricted: Vec<i32>) -> i32 {
let mut result = 0;
let n = n as usize;
let mut graph = vec![vec![];n + 1];
for edge in edges {
let x = edge[0] as usize;
let y = edge[1] as usize;
graph[x].push(y);
graph[y].push(x);
}
let mut queue = VecDeque::new();
let mut visited = HashSet::new();
let mut unreachable = HashSet::with_capacity(restricted.len());
for node in restricted {
unreachable.insert(node as usize);
}
queue.push_back(0);
while !queue.is_empty() {
let node = queue.pop_front().unwrap();
if visited.contains(&node) || unreachable.contains(&node) {
continue;
}
visited.insert(node);
result += 1;
for next in &graph[node] {
queue.push_back(*next);
}
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2368() {
}
}