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:
parent
0f79fcd5ed
commit
e0c94b7af4
1 changed files with 44 additions and 0 deletions
44
cs/find-all-possible-recipes-from-given-supplies.cs
Normal file
44
cs/find-all-possible-recipes-from-given-supplies.cs
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue