-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2115.java
31 lines (31 loc) · 1.11 KB
/
2115.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public List<String> findAllRecipes(
String[] recipes, List<List<String>> ingredients, String[] supplies) {
Map<String, List<String>> g = new HashMap<>();
Map<String, Integer> indeg = new HashMap<>();
for (int i = 0; i < recipes.length; ++i) {
for (String v : ingredients.get(i)) {
g.computeIfAbsent(v, k -> new ArrayList<>()).add(recipes[i]);
}
indeg.put(recipes[i], ingredients.get(i).size());
}
Deque<String> q = new ArrayDeque<>();
for (String s : supplies) {
q.offer(s);
}
List<String> ans = new ArrayList<>();
while (!q.isEmpty()) {
for (int n = q.size(); n > 0; --n) {
String i = q.pollFirst();
for (String j : g.getOrDefault(i, Collections.emptyList())) {
indeg.put(j, indeg.get(j) - 1);
if (indeg.get(j) == 0) {
ans.add(j);
q.offer(j);
}
}
}
}
return ans;
}
}