-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathfind_all_possible_recipes_from_given_supplies.rs
More file actions
66 lines (54 loc) · 1.72 KB
/
find_all_possible_recipes_from_given_supplies.rs
File metadata and controls
66 lines (54 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#[allow(dead_code)]
struct Solution;
use std::collections::{HashMap, HashSet};
impl Solution {
#[allow(dead_code)]
#[allow(clippy::needless_pass_by_value)]
pub fn find_all_recipes(
recipes: Vec<String>,
ingredients: Vec<Vec<String>>,
supplies: Vec<String>,
) -> Vec<String> {
let unique_supplies = supplies
.iter()
.map(String::as_str)
.collect::<HashSet<&str>>();
let mut graph: HashMap<&str, Vec<&str>> = HashMap::new();
for (i, recipe) in recipes.iter().map(String::as_str).enumerate() {
graph.insert(recipe, ingredients[i].iter().map(String::as_str).collect());
}
let mut result = Vec::new();
let mut visited: HashMap<String, bool> = HashMap::new();
for recipe in &recipes {
if Self::dfs(recipe, &graph, &unique_supplies, &mut visited) {
result.push(recipe.clone());
}
}
result
}
fn dfs(
recipe: &str,
graph: &HashMap<&str, Vec<&str>>,
supplies: &HashSet<&str>,
visited: &mut HashMap<String, bool>,
) -> bool {
if visited.contains_key(recipe) {
return *visited.get(recipe).unwrap();
}
visited.insert(recipe.to_string(), false);
for next in graph.get(recipe).unwrap() {
if supplies.contains(next) {
continue;
}
if graph.contains_key(next) {
if !Self::dfs(next, graph, supplies, visited) {
return false;
}
continue;
}
return false;
}
visited.insert(recipe.to_string(), true);
true
}
}