Minimum Time to Collect All Apples in a Tree LeetCode solution in Java

1
class Solution {
2
public int minTime(int n, int[][] edges, List<Boolean> hasApple) {
3
HashMap<Integer, List<Integer>> graph = new HashMap<>(n);
4
for (int edge[] : edges) {
5
int a = edge[0], b = edge[1];
6
graph.putIfAbsent(a, new LinkedList<>());
7
graph.putIfAbsent(b, new LinkedList<>());
8
graph.get(a).add(b);
9
graph.get(b).add(a);
10
}
11

12
boolean[] visited = new boolean[n];
13
Arrays.fill(visited, false);
14

15
int a = move(0, graph, hasApple, n, visited);
16

17
return a == -1 ? 0 : a;
18
}
19

20
public int move(
21
int i,
22
HashMap<Integer, List<Integer>> graph,
23
List<Boolean> hasApple,
24
int n,
25
boolean[] visited) {
26
visited[i] = true;
27
boolean cont = false;
28
if (hasApple.get(i)) {
29
cont = true;
30
}
31

32
List<Integer> list = graph.get(i);
33

34
if (list == null) {
35
return cont ? 0 : -1;
36
}
37
int j = 0;
38
for (int k : list) {
39
if (!visited[k]) {
40
int a = move(k, graph, hasApple, n, visited);
41
if (a != -1) {
42
j += 2 + a;
43
}
44
}
45
}
46
if (j == 0 && cont) return 0;
47
return j == 0 ? -1 : j;
48
}
49
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0