forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind All Possible Recipes from Given Supplies.java
52 lines (42 loc) · 1.44 KB
/
Find All Possible Recipes from Given Supplies.java
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
// Runtime: 63 ms (Top 70.73%) | Memory: 73 MB (Top 78.21%)
class Solution {
private static final int NOT_VISITED = 0;
private static final int VISITING = 1;
private static final int VISITED = 2;
public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) {
Map<String, Integer> status = new HashMap<>();
Map<String, List<String>> prereqs = new HashMap<>();
for (int i = 0; i < recipes.length; ++ i) {
status.put(recipes[i], NOT_VISITED);
prereqs.put(recipes[i], ingredients.get(i));
}
for (String s: supplies) {
status.put(s, VISITED);
}
List<String> output = new ArrayList<>();
for (String s: recipes) {
dfs (s, prereqs, status, output);
}
return output;
}
public boolean dfs(String s, Map<String, List<String>> prereqs, Map<String, Integer> status, List<String> output) {
if (!status.containsKey(s)) {
return false;
}
if (status.get(s) == VISITING) {
return false;
}
if (status.get(s) == VISITED) {
return true;
}
status.put(s, VISITING);
for (String p: prereqs.get(s)) {
if (!dfs(p, prereqs, status, output)) {
return false;
}
}
status.put(s, VISITED);
output.add(s);
return true;
}
}