Paste: 2115
Author: | Cai Ji |
Mode: | c++ |
Date: | Wed, 11 May 2022 14:49:25 |
Plain Text |
class Solution {
private:
unordered_map<string, int> suppHash, memo;
unordered_map<string, vector<string> > recipeHash;
public:
vector<string> findAllRecipes(vector<string>& recipes, vector<vector<string>>& ingredients, vector<string>& supplies) {
vector<string> res;
for (string supply : supplies)
suppHash[supply]++;
for (int i = 0; i < recipes.size(); i++) {
recipeHash[recipes[i]] = ingredients[i];
}
for (string rec : recipes) {
if (dfs(rec))
res.push_back(rec);
}
return res;
}
bool dfs(string recipe) {
if (memo[recipe])
return memo[recipe] == 1 ? true : false;
vector<string> recList = recipeHash[recipe];
for (string rec : recList) {
if (!suppHash[rec]) {
if (recipeHash.find(rec) == recipeHash.end() && !dfs(rec)) {
memo[rec] = -1;
return false;
}
}
}
memo[recipe] = 1;
return true;
}
};
New Annotation