Skip to content

Commit 567ce7f

Browse files
authored
Create 2115-find-all-possible-recipes-from-given-supplies.js
1 parent 01b8059 commit 567ce7f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @param {string[]} recipes
3+
* @param {string[][]} ingredients
4+
* @param {string[]} supplies
5+
* @return {string[]}
6+
*/
7+
const findAllRecipes = function(recipes, ingredients, supplies) {
8+
const set = new Set(supplies), res = [], graph = {}, n = recipes.length
9+
const inDegree = {}
10+
for(let x of recipes) inDegree[x] = 0
11+
for(let i = 0; i < n; i++) {
12+
for(let j = 0; j < ingredients[i].length; j++) {
13+
const ing = ingredients[i][j]
14+
if(!set.has(ing)) {
15+
if (graph[ing] == null) graph[ing] = []
16+
graph[ing].push(recipes[i])
17+
inDegree[recipes[i]]++
18+
}
19+
}
20+
}
21+
// Kahn's Algorithm
22+
const q = []
23+
for(let x in inDegree) {
24+
if (inDegree[x] === 0) q.push(x)
25+
}
26+
while(q.length) {
27+
const len = q.length
28+
for(let i = 0; i < len; i++) {
29+
const cur = q.pop()
30+
res.push(cur)
31+
for(let next of (graph[cur] || [])) {
32+
inDegree[next]--
33+
if(inDegree[next] === 0) {
34+
q.push(next)
35+
}
36+
}
37+
}
38+
}
39+
return res
40+
};

0 commit comments

Comments
 (0)