Approach
Breadth-first search
For Find All Possible Recipes from Given Supplies, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 40 lines of Java from the credited upstream file 2115.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients,3 String[] supplies) {4 List<String> ans = new ArrayList<>();5 Set<String> suppliesSet = new HashSet<>();6 for (final String supply : supplies)7 suppliesSet.add(supply);8 Map<String, List<String>> graph = new HashMap<>();9 Map<String, Integer> inDegrees = new HashMap<>();10 11 12 for (int i = 0; i < recipes.length; ++i)13 for (final String ingredient : ingredients.get(i))14 if (!suppliesSet.contains(ingredient)) {15 graph.putIfAbsent(ingredient, new ArrayList<>());16 graph.get(ingredient).add(recipes[i]);17 inDegrees.merge(recipes[i], 1, Integer::sum);18 }19 20 21 Queue<String> q = Arrays.stream(recipes)22 .filter(recipe -> inDegrees.getOrDefault(recipe, 0) == 0)23 .collect(Collectors.toCollection(ArrayDeque::new));24 25 while (!q.isEmpty()) {26 final String u = q.poll();27 ans.add(u);28 if (!graph.containsKey(u))29 continue;30 for (final String v : graph.get(u)) {31 inDegrees.merge(v, -1, Integer::sum);32 if (inDegrees.get(v) == 0)33 q.offer(v);34 }35 }36 37 return ans;38 }39}40