Advertisement
ivandrofly

NeetCode.FindAllPossibleRecipesFromGiveSupplies

Mar 28th, 2025
481
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.86 KB | None | 0 0
  1. // types of arrays
  2.  
  3. int[,] array2D = new[,]
  4. {
  5.     { 1, 1 }, { 1, 1 }
  6. };
  7. int[][] jagged = new int[][]
  8. {
  9.     [1, 1],
  10.     [1, 1],
  11.     [1, 1]
  12. };
  13.  
  14. // string[,] ingredients = [["yeast", "flour"], ["bread", "meat"], ["sandwich", "meat", "bread"]];
  15.  
  16. string[] recipes = ["bread", "sandwich", "meat"];
  17. string[][] ingredients = new string[][] { ["yeast", "flour"], ["bread", "meat"], ["sandwich", "meat", "bread"] };
  18. string[] supplies = ["yeast", "flour", "meat"];
  19.  
  20. Console.WriteLine(String.Join(",", FindAllRecipes(recipes, ingredients, supplies)));
  21. return;
  22.  
  23. static IEnumerable<string> FindAllRecipes(string[] recipes, string[][] ingredients, string[] supplies)
  24. {
  25.     // all supplies are marked as cookable
  26.     var canCook = supplies.ToDictionary(s => s, _ => true);
  27.     var recipeIndex = recipes.Zip(Enumerable.Range(0, recipes.Length),
  28.         (r, i) => (r, i)).ToDictionary(zip => zip.r, zip => zip.i);
  29.  
  30.     List<string> result = [];
  31.  
  32.     foreach (string recipe in recipes)
  33.     {
  34.         if (Dfs(recipe))
  35.         {
  36.             result.Add(recipe);
  37.         }
  38.     }
  39.  
  40.     return result;
  41.  
  42.     bool Dfs(string recipe)
  43.     {
  44.         if (canCook.TryGetValue(recipe, out _))
  45.         {
  46.             return canCook[recipe];
  47.         }
  48.  
  49.         canCook[recipe] = false; // handles circular dependencies
  50.  
  51.         if (!recipeIndex.ContainsKey(recipe))
  52.         {
  53.             return false;
  54.         }
  55.  
  56.         foreach (string ingredient in ingredients[recipeIndex[recipe]])
  57.         {
  58.             if (!canCook.TryGetValue(ingredient, out _))
  59.             {
  60.                 return false;
  61.             }
  62.         }
  63.  
  64.         canCook[recipe] = true;
  65.  
  66.         return canCook[recipe];
  67.     }
  68. }
  69.  
  70. // output:
  71. // ["bread", "sandwich", "burger"]
  72.  
  73. // INFORMATION:
  74. // Find All Possible Recipes from Given Supplies - Leetcode 2115 - Python
  75. // https://youtu.be/AQrsAc3EcyQ
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement