Advertisement
thewitchking

Untitled

Dec 14th, 2023
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. class Solution {
  2.     public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) {
  3.         List<String> ans = new ArrayList<>();
  4.        
  5.         Set<String> available = new HashSet<>(Arrays.asList(supplies));
  6.         Map<String, Set<String>> ingredientToRecipes = new HashMap<>();
  7.         Map<String, Integer> inDegree = new HashMap<>();
  8.         for (int i = 0; i < recipes.length; ++i) {
  9.             int nonAvailable = 0;
  10.             for (String ing : ingredients.get(i)) {
  11.                 if (!available.contains(ing)) {
  12.                     ingredientToRecipes.computeIfAbsent(ing, s -> new HashSet<>()).add(recipes[i]);
  13.                     ++nonAvailable;
  14.                 }
  15.             }
  16.             if (nonAvailable == 0) {
  17.                 ans.add(recipes[i]);
  18.             }else {
  19.                 inDegree.put(recipes[i], nonAvailable);
  20.             }
  21.         }
  22.        
  23.         for (int i = 0; i < ans.size(); ++i) {
  24.             String recipe = ans.get(i);
  25.             if (ingredientToRecipes.containsKey(recipe)) {
  26.                 for (String rcp : ingredientToRecipes.remove(recipe)) {
  27.                     if (inDegree.merge(rcp, -1, Integer::sum) == 0) {
  28.                         ans.add(rcp);
  29.                     }
  30.                 }
  31.             }
  32.         }
  33.         return ans;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement