-
-
Notifications
You must be signed in to change notification settings - Fork 445
Expand file tree
/
Copy pathFindAllPossibleRecipes.java
More file actions
72 lines (62 loc) · 2.53 KB
/
FindAllPossibleRecipes.java
File metadata and controls
72 lines (62 loc) · 2.53 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
67
68
69
70
71
72
import java.util.*;
public class FindAllPossibleRecipes {
public List<String> findAllRecipes(
String[] recipes,
List<List<String>> ingredients,
String[] supplies
) {
// Store available supplies
Set<String> availableSupplies = new HashSet<>();
// Map recipe to its index
Map<String, Integer> recipeToIndex = new HashMap<>();
// Map ingredient to recipes that need it
Map<String, List<String>> dependencyGraph = new HashMap<>();
// Initialize available supplies
for (String supply : supplies) {
availableSupplies.add(supply);
}
// Create recipe to index mapping
for (int idx = 0; idx < recipes.length; idx++) {
recipeToIndex.put(recipes[idx], idx);
}
// Count of non-supply ingredients needed for each recipe
int[] inDegree = new int[recipes.length];
// Build dependency graph
for (int recipeIdx = 0; recipeIdx < recipes.length; recipeIdx++) {
for (String ingredient : ingredients.get(recipeIdx)) {
if (!availableSupplies.contains(ingredient)) {
// Add edge: ingredient -> recipe
dependencyGraph.putIfAbsent(
ingredient,
new ArrayList<String>()
);
dependencyGraph.get(ingredient).add(recipes[recipeIdx]);
inDegree[recipeIdx]++;
}
}
}
// Start with recipes that only need supplies
Queue<Integer> queue = new LinkedList<>();
for (int recipeIdx = 0; recipeIdx < recipes.length; recipeIdx++) {
if (inDegree[recipeIdx] == 0) {
queue.add(recipeIdx);
}
}
// Process recipes in topological order
List<String> createdRecipes = new ArrayList<>();
while (!queue.isEmpty()) {
int recipeIdx = queue.poll();
String recipe = recipes[recipeIdx];
createdRecipes.add(recipe);
// Skip if no recipes depend on this one
if (!dependencyGraph.containsKey(recipe)) continue;
// Update recipes that depend on current recipe
for (String dependentRecipe : dependencyGraph.get(recipe)) {
if (--inDegree[recipeToIndex.get(dependentRecipe)] == 0) {
queue.add(recipeToIndex.get(dependentRecipe));
}
}
}
return createdRecipes;
}
}