|
| 1 | +/** |
| 2 | + * 2115. Find All Possible Recipes from Given Supplies |
| 3 | + * https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You have information about n different recipes. You are given a string array recipes and a 2D |
| 7 | + * string array ingredients. The ith recipe has the name recipes[i], and you can create it if you |
| 8 | + * have all the needed ingredients from ingredients[i]. A recipe can also be an ingredient for |
| 9 | + * other recipes, i.e., ingredients[i] may contain a string that is in recipes. |
| 10 | + * |
| 11 | + * You are also given a string array supplies containing all the ingredients that you initially |
| 12 | + * have, and you have an infinite supply of all of them. |
| 13 | + * |
| 14 | + * Return a list of all the recipes that you can create. You may return the answer in any order. |
| 15 | + * |
| 16 | + * Note that two recipes may contain each other in their ingredients. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {string[]} recipes |
| 21 | + * @param {string[][]} ingredients |
| 22 | + * @param {string[]} supplies |
| 23 | + * @return {string[]} |
| 24 | + */ |
| 25 | +var findAllRecipes = function(recipes, ingredients, supplies) { |
| 26 | + const available = new Set(supplies); |
| 27 | + const recipeGraph = new Map(); |
| 28 | + const inDegree = new Map(); |
| 29 | + const queue = []; |
| 30 | + const result = []; |
| 31 | + |
| 32 | + recipes.forEach((recipe, index) => { |
| 33 | + inDegree.set(recipe, ingredients[index].length); |
| 34 | + ingredients[index].forEach(ing => { |
| 35 | + if (!recipeGraph.has(ing)) recipeGraph.set(ing, []); |
| 36 | + recipeGraph.get(ing).push(recipe); |
| 37 | + }); |
| 38 | + }); |
| 39 | + |
| 40 | + available.forEach(supply => { |
| 41 | + if (recipeGraph.has(supply)) { |
| 42 | + recipeGraph.get(supply).forEach(recipe => { |
| 43 | + const count = inDegree.get(recipe) - 1; |
| 44 | + inDegree.set(recipe, count); |
| 45 | + if (count === 0) queue.push(recipe); |
| 46 | + }); |
| 47 | + } |
| 48 | + }); |
| 49 | + |
| 50 | + while (queue.length) { |
| 51 | + const currentRecipe = queue.shift(); |
| 52 | + result.push(currentRecipe); |
| 53 | + if (recipeGraph.has(currentRecipe)) { |
| 54 | + recipeGraph.get(currentRecipe).forEach(nextRecipe => { |
| 55 | + const count = inDegree.get(nextRecipe) - 1; |
| 56 | + inDegree.set(nextRecipe, count); |
| 57 | + if (count === 0) queue.push(nextRecipe); |
| 58 | + }); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return result; |
| 63 | +}; |
0 commit comments