Skip to content

Commit 88e141e

Browse files
authored
Create find-all-possible-recipes-from-given-supplies.py
1 parent 26d64a7 commit 88e141e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Time: O(|E|)
2+
# Space: O(|E|)
3+
4+
import collections
5+
import itertools
6+
7+
class Solution(object):
8+
def findAllRecipes(self, recipes, ingredients, supplies):
9+
"""
10+
:type recipes: List[str]
11+
:type ingredients: List[List[str]]
12+
:type supplies: List[str]
13+
:rtype: List[str]
14+
"""
15+
indegree = collections.defaultdict(int)
16+
adj = collections.defaultdict(list)
17+
for r, ingredient in itertools.izip(recipes, ingredients):
18+
indegree[r] = len(ingredient)
19+
for ing in ingredient:
20+
adj[ing].append(r)
21+
result = []
22+
recipes = set(recipes)
23+
q = supplies
24+
while q:
25+
new_q = []
26+
for u in q:
27+
if u in recipes:
28+
result.append(u)
29+
for v in adj[u]:
30+
indegree[v] -= 1
31+
if not indegree[v]:
32+
new_q.append(v)
33+
q = new_q
34+
return result

0 commit comments

Comments
 (0)