题目
解法1:
利用dfs,找出所有的在摘苹果的过程中会被访问的边。这些被访问的边数*2就是答案
这种做法需要保存当前路径,当发现当前路径包含苹果时,将这些边加入访问列表。这样做的坏处在于,每条边可能被加入多次,意味着时间复杂度的增加,事实证明这种做法确实不都快,刚刚过TLE的线。但利用字典或者set,还是可以不重复的记录摘苹果时需要被访问的边
class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
# main idea: find the edges has been used through dfs, the total time is the number of used_edges*2
# dfs to visited every node
def dfs(node,path):
# append current node to path
path.append(node)
visited[node] = True
# if current node has apple, we add the edges in the path from root to current node
if hasApple[node]:
for i in range(1,len(path)):
edge = (path[i-1],path[i])
used_edge[edge] = True
for nei in graph[node]:
if not visited[nei]:
dfs(nei,path[:])
graph = collections.defaultdict(list)
for i,edge in enumerate(edges):
graph[edge[0]].append(edge[1])
graph[edge[1]