Skip to content

Find All Possible Recipes from Given Supplies

LeetCode

01 · Question

Given recipes and their ingredient lists, and initial supplies, return all recipes you can make. A recipe becomes available when all its ingredients are available.

02 · Solution

Reference solution

1from collections import deque
2
3def findAllRecipes(recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
4 graph = {}
5 indeg = {r: 0 for r in recipes}
6
7 for r, ing in zip(recipes, ingredients):
8 for x in ing:
9 graph.setdefault(x, []).append(r)
10 if x not in indeg:
11 indeg[r] += 1
12
13 q = deque(supplies)
14 res = []
15 while q:
16 item = q.popleft()
17 for r in graph.get(item, []):
18 indeg[r] -= 1
19 if indeg[r] == 0:
20 res.append(r)
21 q.append(r)
22 return res