You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class Solution {
public int minTime(int n, int[][] edges, List<Boolean> hasApple) {
// convert hasApple to map
Map<Integer, Boolean> appleMap = new HashMap<>();
for (int i = 0; i < hasApple.size(); i++) {
appleMap.put(i, hasApple.get(i));
}
// convert edges to map
Map<Integer, List<Integer>> edgeMap = new HashMap<>();
for (int[] edge : edges) {
int from = edge[0];
int to = edge[1];
List<Integer> list = edgeMap.getOrDefault(from, new ArrayList<>());
list.add(to);
edgeMap.put(from, list);
List<Integer> list2 = edgeMap.getOrDefault(to, new ArrayList<>());
list2.add(from);
edgeMap.put(to, list2);
}
// post order traversal
return postorder(edgeMap, appleMap, -1, 0);
}
private int postorder(Map<Integer, List<Integer>> edgeMap, Map<Integer, Boolean> appleMap, int pre, int cur) {
if (edgeMap.get(cur).size() == 1 && edgeMap.get(cur).get(0) == pre) {
return appleMap.get(cur) ? 2 : 0;
}
int sum = 0;
for (int next : edgeMap.get(cur)) {
if (next == pre) {
continue;
}
int time = postorder(edgeMap, appleMap, cur, next);
if (time > 0) {
sum += time;
}
}
if (cur != 0 && (sum > 0 || appleMap.get(cur))) {
sum += 2;
}
return sum;
}
}
这道题并不难,我花了17分钟就AC了。但因为觉得有些注意的点,就打算记录下来。
Tips:
这是竞赛中学到的The text was updated successfully, but these errors were encountered: