Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // types of arrays
- int[,] array2D = new[,]
- {
- { 1, 1 }, { 1, 1 }
- };
- int[][] jagged = new int[][]
- {
- [1, 1],
- [1, 1],
- [1, 1]
- };
- // string[,] ingredients = [["yeast", "flour"], ["bread", "meat"], ["sandwich", "meat", "bread"]];
- string[] recipes = ["bread", "sandwich", "meat"];
- string[][] ingredients = new string[][] { ["yeast", "flour"], ["bread", "meat"], ["sandwich", "meat", "bread"] };
- string[] supplies = ["yeast", "flour", "meat"];
- Console.WriteLine(String.Join(",", FindAllRecipes(recipes, ingredients, supplies)));
- return;
- static IEnumerable<string> FindAllRecipes(string[] recipes, string[][] ingredients, string[] supplies)
- {
- // all supplies are marked as cookable
- var canCook = supplies.ToDictionary(s => s, _ => true);
- var recipeIndex = recipes.Zip(Enumerable.Range(0, recipes.Length),
- (r, i) => (r, i)).ToDictionary(zip => zip.r, zip => zip.i);
- List<string> result = [];
- foreach (string recipe in recipes)
- {
- if (Dfs(recipe))
- {
- result.Add(recipe);
- }
- }
- return result;
- bool Dfs(string recipe)
- {
- if (canCook.TryGetValue(recipe, out _))
- {
- return canCook[recipe];
- }
- canCook[recipe] = false; // handles circular dependencies
- if (!recipeIndex.ContainsKey(recipe))
- {
- return false;
- }
- foreach (string ingredient in ingredients[recipeIndex[recipe]])
- {
- if (!canCook.TryGetValue(ingredient, out _))
- {
- return false;
- }
- }
- canCook[recipe] = true;
- return canCook[recipe];
- }
- }
- // output:
- // ["bread", "sandwich", "burger"]
- // INFORMATION:
- // Find All Possible Recipes from Given Supplies - Leetcode 2115 - Python
- // https://youtu.be/AQrsAc3EcyQ
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement