Advertisement
thewitchking

Untitled

Mar 26th, 2025
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. class Solution {
  2.     public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) {
  3.         Set<String> availableSupplies = new HashSet<>(Arrays.asList(supplies));
  4.         Map<String, List<String>> ingredientToRecipes = new HashMap<>();
  5.         Map<String, Integer> inDegree = new HashMap<>();
  6.         Map<String, List<String>> recipeToIngredients = new HashMap<>();
  7.  
  8.         for (int i = 0; i < recipes.length; i++) {
  9.             String recipe = recipes[i];
  10.             List<String> recipeIngredients = ingredients.get(i);
  11.             recipeToIngredients.put(recipe, recipeIngredients);
  12.             inDegree.put(recipe, recipeIngredients.size());
  13.  
  14.             for (String ingredient : recipeIngredients) {
  15.                 ingredientToRecipes.computeIfAbsent(ingredient, k -> new ArrayList<>()).add(recipe);
  16.             }
  17.         }
  18.  
  19.         Queue<String> queue = new LinkedList<>(availableSupplies);
  20.         List<String> result = new ArrayList<>();
  21.  
  22.         while (!queue.isEmpty()) {
  23.             String current = queue.poll();
  24.  
  25.             if (recipeToIngredients.containsKey(current)) {
  26.                 result.add(current);
  27.             }
  28.  
  29.             if (ingredientToRecipes.containsKey(current)) {
  30.                 for (String dependentRecipe : ingredientToRecipes.get(current)) {
  31.                     inDegree.put(dependentRecipe, inDegree.get(dependentRecipe) - 1);
  32.                     if (inDegree.get(dependentRecipe) == 0) {
  33.                         queue.add(dependentRecipe);
  34.                     }
  35.                 }
  36.             }
  37.         }
  38.  
  39.         return result;
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement