|
| 1 | +from collections import defaultdict, deque |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + def findAllRecipes( |
| 6 | + self, recipes: list[str], ingredients: list[list[str]], supplies: list[str] |
| 7 | + ) -> list[str]: |
| 8 | + supplies = set(supplies) |
| 9 | + graph = defaultdict(set) # ingredient -> recipes |
| 10 | + in_degree = defaultdict(int) # recipe -> in-degree |
| 11 | + queue = deque() |
| 12 | + |
| 13 | + for recipe, ingredient in zip(recipes, ingredients): |
| 14 | + not_available = 0 |
| 15 | + for i in ingredient: |
| 16 | + if i not in supplies: |
| 17 | + not_available += 1 |
| 18 | + graph[i].add(recipe) |
| 19 | + if not_available == 0: |
| 20 | + queue.append(recipe) |
| 21 | + else: |
| 22 | + in_degree[recipe] = not_available |
| 23 | + |
| 24 | + result = [] |
| 25 | + while queue: |
| 26 | + recipe = queue.popleft() |
| 27 | + result.append(recipe) |
| 28 | + for neighbour in graph[recipe]: |
| 29 | + in_degree[neighbour] -= 1 |
| 30 | + if in_degree[neighbour] == 0: |
| 31 | + queue.append(neighbour) |
| 32 | + return result |
| 33 | + |
| 34 | + |
| 35 | +def main(): |
| 36 | + recipes = ['bread'] |
| 37 | + ingredients = [['yeast', 'flour']] |
| 38 | + supplies = ['yeast', 'flour', 'corn'] |
| 39 | + assert Solution().findAllRecipes(recipes, ingredients, supplies) == ['bread'] |
| 40 | + |
| 41 | + recipes = ['bread', 'sandwich'] |
| 42 | + ingredients = [['yeast', 'flour'], ['bread', 'meat']] |
| 43 | + supplies = ['yeast', 'flour', 'meat'] |
| 44 | + assert Solution().findAllRecipes(recipes, ingredients, supplies) == ['bread', 'sandwich'] |
| 45 | + |
| 46 | + recipes = ['bread', 'sandwich', 'burger'] |
| 47 | + ingredients = [['yeast', 'flour'], ['bread', 'meat'], ['sandwich', 'meat', 'bread']] |
| 48 | + supplies = ['yeast', 'flour', 'meat'] |
| 49 | + assert Solution().findAllRecipes(recipes, ingredients, supplies) == ['bread', 'sandwich', 'burger'] |
| 50 | + |
| 51 | + |
| 52 | +if __name__ == '__main__': |
| 53 | + main() |
0 commit comments