cs: add «2115. Find All Possible Recipes from Given Supplies»

URL:	https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-03-21 23:02:05 +01:00
parent 0f79fcd5ed
commit e0c94b7af4
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,44 @@
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;
}
}