URL: https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/ Signed-off-by: Matej Focko <me@mfocko.xyz>
44 lines
1.4 KiB
C#
44 lines
1.4 KiB
C#
public class Solution {
|
|
public IList<string> FindAllRecipes(
|
|
string[] recipes, IList<IList<string>> ingredients, string[] supplies
|
|
) {
|
|
var available = new HashSet<string>(supplies);
|
|
|
|
var indices = new Dictionary<string, int>();
|
|
for (var i = 0; i < recipes.Length; ++i) {
|
|
indices[recipes[i]] = i;
|
|
}
|
|
|
|
var dependencies = new Dictionary<string, List<string>>();
|
|
var inDegree = new int[recipes.Length];
|
|
|
|
foreach (var (idx, ingredient) in Enumerable.Range(0, recipes.Length).SelectMany(i => ingredients[i].Select(x => (i, x)))) {
|
|
if (available.Contains(ingredient)) {
|
|
continue;
|
|
}
|
|
|
|
dependencies.TryAdd(ingredient, []);
|
|
dependencies[ingredient].Add(recipes[idx]);
|
|
++inDegree[idx];
|
|
}
|
|
|
|
var q = new Queue<int>(Enumerable.Range(0, recipes.Length).Where(i => inDegree[i] == 0));
|
|
|
|
var created = new List<string>();
|
|
while (q.TryDequeue(out var idx)) {
|
|
var recipe = recipes[idx];
|
|
created.Add(recipe);
|
|
|
|
if (dependencies.TryGetValue(recipe, out var dependents)) {
|
|
foreach (var dep in dependents) {
|
|
if (--inDegree[indices[dep]] == 0) {
|
|
q.Enqueue(indices[dep]);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
return created;
|
|
}
|
|
}
|