|
| 1 | +package solutions; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +// [Problem] https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies |
| 6 | +class FindAllPossibleRecipes { |
| 7 | + public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) { |
| 8 | + List<String> availableRecipes = new ArrayList<>(); |
| 9 | + Set<String> availableIngredients = new HashSet<>(); |
| 10 | + Collections.addAll(availableIngredients, supplies); |
| 11 | + Map<String, List<String>> recipesPerIngredient = new HashMap<>(); |
| 12 | + Map<String, Integer> inDegree = new HashMap<>(); |
| 13 | + for (int i = 0; i < recipes.length; i++) { |
| 14 | + String recipe = recipes[i]; |
| 15 | + int unavailableIngredients = 0; |
| 16 | + for (String ingredient : ingredients.get(i)) { |
| 17 | + if (!availableIngredients.contains(ingredient)) { |
| 18 | + recipesPerIngredient.putIfAbsent(ingredient, new ArrayList<>()); |
| 19 | + recipesPerIngredient.get(ingredient).add(recipe); |
| 20 | + unavailableIngredients++; |
| 21 | + } |
| 22 | + } |
| 23 | + if (unavailableIngredients == 0) { |
| 24 | + availableRecipes.add(recipe); |
| 25 | + } else { |
| 26 | + inDegree.put(recipe, unavailableIngredients); |
| 27 | + } |
| 28 | + } |
| 29 | + for (int i = 0; i < availableRecipes.size(); i++) { |
| 30 | + String availableIngredient = availableRecipes.get(i); |
| 31 | + if (recipesPerIngredient.containsKey(availableIngredient)) { |
| 32 | + List<String> recipesUsingThis = recipesPerIngredient.get(availableIngredient); |
| 33 | + for (String recipe : recipesUsingThis) { |
| 34 | + inDegree.put(recipe, inDegree.get(recipe) - 1); |
| 35 | + if (inDegree.get(recipe) == 0) { |
| 36 | + availableRecipes.add(recipe); |
| 37 | + } |
| 38 | + } |
| 39 | + recipesPerIngredient.remove(availableIngredient); |
| 40 | + } |
| 41 | + } |
| 42 | + return availableRecipes; |
| 43 | + } |
| 44 | + |
| 45 | + // Test |
| 46 | + public static void main(String[] args) { |
| 47 | + FindAllPossibleRecipes solution = new FindAllPossibleRecipes(); |
| 48 | + |
| 49 | + String[] recipes = {"bread", "sandwich"}; |
| 50 | + List<List<String>> ingredients = List.of(List.of("yeast", "flour"), List.of("bread", "meat")); |
| 51 | + String[] supplies = {"yeast", "flour", "meat"}; |
| 52 | + List<String> expectedOutput = List.of("bread", "sandwich"); |
| 53 | + List<String> actualOutput = solution.findAllRecipes(recipes, ingredients, supplies); |
| 54 | + |
| 55 | + System.out.println("Test passed? " + expectedOutput.equals(actualOutput)); |
| 56 | + } |
| 57 | +} |
0 commit comments