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
- 39 lines of C++ from the credited upstream file 2115.cpp.
- The implementation visibly relies on sequence storage, hash 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:3 vector<string> findAllRecipes(vector<string>& recipes,4 vector<vector<string>>& ingredients,5 vector<string>& supplies) {6 vector<string> ans;7 unordered_set<string> suppliesSet(supplies.begin(), supplies.end());8 unordered_map<string, vector<string>> graph;9 unordered_map<string, int> inDegrees;10 queue<string> q;11 12 13 for (int i = 0; i < recipes.size(); ++i)14 for (const string& ingredient : ingredients[i])15 if (!suppliesSet.contains(ingredient)) {16 graph[ingredient].push_back(recipes[i]);17 ++inDegrees[recipes[i]];18 }19 20 21 for (const string& recipe : recipes)22 if (!inDegrees.contains(recipe))23 q.push(recipe);24 25 while (!q.empty()) {26 const string u = q.front();27 q.pop();28 ans.push_back(u);29 if (!graph.contains(u))30 continue;31 for (const string& v : graph[u])32 if (--inDegrees[v] == 0)33 q.push(v);34 }35 36 return ans;37 }38};39