题目是LeetCode第188场周赛的第三题,链接:1443. 收集树上所有苹果的最少时间。具体描述见原题。
这道题可以直接用DFS来解决。首先需要形成图的结构,需要注意的是这是一个无向图,构建图的时候要注意这一点。然后定义一个dfs(int node, List<Boolean> hasApple)
函数,从节点0
开始,遍历当前节点的所有未被访问过的邻接节点nextNode
,累积结果result+=dfs(nextNode, hasApple)
,假如结果result==0
,则根据当前节点是否有苹果直接返回2
或0
,否则直接返回result+2
,也就是路径必然会经过当前节点。
因为需要遍历所有边(每条边会被访问两次),所以时间复杂度为 O ( n ) O(n) O(n),空间复杂度为 O ( n ) O(n) O(n)。
JAVA版代码如下:
class Solution {
private Map<Integer, List<Integer>> root2son;
private boolean[] visited;
private int visit(int node, List<Boolean> hasApple) {
visited[node] = true;
List<Integer> lst = root2son.get(node);
int result = 0;
for (int nextNode : lst) {
if (!visited[nextNode]) {
result += visit(nextNode, hasApple);
}
}
if (result == 0) {
return hasApple.get(node) ? 2 : 0;
}
else {
return result + 2;
}
}
public int minTime(int n, int[][] edges, List<Boolean> hasApple) {
root2son = new HashMap<>();
visited = new boolean[n];
for (int[] edge : edges) {
if (root2son.containsKey(edge[0])) {
root2son.get(edge[0]).add(edge[1]);
}
else {
List<Integer> list = new ArrayList<>();
list.add(edge[1]);
root2son.put(edge[0], list);
}
if (root2son.containsKey(edge[1])) {
root2son.get(edge[1]).add(edge[0]);
}
else {
List<Integer> list = new ArrayList<>();
list.add(edge[0]);
root2son.put(edge[1], list);
}
}
int result = visit(0, hasApple);
return result == 0 ? 0 : result - 2;
}
}
提交结果如下:
注:这道题比赛那会因为测试数据的特殊性所以可以用从底到顶去做,时间可以很短(比如4ms),但是后来因为官方又加了测试数据导致这些方法都失效了,所以就不要太care这里的执行用时为啥比不过人家了。。。
Python版代码如下:
class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
figure = collections.defaultdict(list)
visited = [False] * n
for edge in edges:
figure[edge[0]].append(edge[1])
figure[edge[1]].append(edge[0])
def dfs(node):
visited[node] = True
res = 0
for nextNode in figure[node]:
if not visited[nextNode]:
res += dfs(nextNode)
if res == 0:
return 2 if hasApple[node] else 0
else:
return res + 2
result = dfs(0)
return 0 if result == 0 else result - 2
提交结果如下: