billy_don
Senior Member
Fen bày ra mà fen không dọn những thằng sau dfs tới nó thấy marked visited rồi nó ko tính nữa, sửa lại logic chỗ visited. Nên sửa lại đi tới đâu mark hẳn visited tới đó, check hết list ingredients thì hốt lại.Các bác debug giúp em với, em không rõ sai chỗ nào mà không pass được.Java:class Solution { public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) { Map<String, Boolean> hasSupplies = new HashMap<>(); for (String supply : supplies) { hasSupplies.put(supply, true); } Map<String, List<String>> ingredientTree = buildIngredientTree(recipes, ingredients); List<String> canMake = new ArrayList<>(); for (String recipe : recipes) { if (canCreateThis(recipe, ingredientTree, hasSupplies, new HashMap<>())) { canMake.add(recipe); } } return canMake; } public Map<String, List<String>> buildIngredientTree(String[] recipes, List<List<String>> ingredients) { Map<String, List<String>> ingredientTree = new HashMap<>(); for (int i = 0; i < recipes.length; i++) { for (String ingredient : ingredients.get(i)) { List<String> require = ingredientTree.getOrDefault(recipes[i], new ArrayList<>()); require.add(ingredient); ingredientTree.put(recipes[i], require); } } return ingredientTree; } public boolean canCreateThis(String recipe, Map<String, List<String>> ingredientTree, Map<String, Boolean> hasSupplies, Map<String, Boolean> isVisited) { if (hasSupplies.get(recipe) != null) { return hasSupplies.get(recipe); } if (null != isVisited.get(recipe)) { return false; } boolean canCreate = (ingredientTree.get(recipe) != null); for (String ingredient : ingredientTree.getOrDefault(recipe, new ArrayList<>())) { if (null == isVisited.get(ingredient)) { isVisited.put(ingredient, true); canCreate &= canCreateThis(ingredient, ingredientTree, hasSupplies, isVisited); } } hasSupplies.put(recipe, canCreate); return canCreate; } }
Java:
public boolean canCreateThis(String recipe, Map<String, List<String>> ingredientTree,
Map<String, Boolean> hasSupplies, Map<String, Boolean> isVisited) {
if (hasSupplies.get(recipe) != null) {
return hasSupplies.get(recipe);
}
if (null != isVisited.get(recipe)) {
return false;
}
[B]isVisited.put(recipe, true);[/B]
boolean canCreate = (ingredientTree.get(recipe) != null);
for (String ingredient : ingredientTree.getOrDefault(recipe, new ArrayList<>())) {
[B]if (!canCreateThis(ingredient, ingredientTree, hasSupplies, isVisited)) {
isVisited.remove(ingredient);
return false;
}[/B]
}
[B]isVisited.remove(recipe);[/B]
hasSupplies.put(recipe, canCreate);
return canCreate;
}
Mà mấy cái visited dùng thẳng set luôn dùng hashmap true false rồi còn check null như kia hơi rườm rà , chỗ build tree kia xem lại tiếp nha add thẳng cái cục ingredients luôn sao phải init, loops rồi add nhìn hơi mệt.
Last edited: