[leetcode] 1443. Minimum Time to Collect All Apples in a Tree

Description

Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend in order to collect all apples in the tree starting at vertex 0 and coming back to this vertex.

The edges of the undirected tree are given in the array edges, where edges[i] = [fromi, toi] means that exists an edge connecting the vertices fromi and toi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple, otherwise, it does not have any apple.

Example 1:
在这里插入图片描述

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]
Output: 8 
Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.  

Example 2:
在这里插入图片描述

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]
Output: 6
Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. 

Example 3:

Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]
Output: 0

Constraints:

  • 1 <= n <= 10^5
  • edges.length == n-1
  • edges[i].length == 2
  • 0 <= fromi, toi <= n-1
  • fromi < toi
  • hasApple.length == n

分析

题目的意思是:给你定一颗二叉树,求出遍历所有苹果的最小时间。这道题的二叉树是用边的形式给出来的,挺新颖的,当然我也没做出来。大概思路是要建立一个无向图,进行深度优先搜索,然后记录代价并求和就行了。注意无向图是有环的,不要陷入环里面去了,所以要比较一下当前结点的parent是否等于child。下面的代码中如果遍历的是非根结点

hasApple[parent] = True

主要是递归计算回传的时候记录中间经过的边,可以说是一个小trick了,我也想不到哈哈哈。

代码

class Solution:
    def solve(self,routes,hasApple,idx,parent):
        cost=0
        for child in routes[idx]:
            if(child!=parent):
                cost+=self.solve(routes,hasApple,child,idx)
        
        if(idx!=0 and hasApple[idx]):
            hasApple[parent]=True
            return cost+2
        return cost
        
    def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
        routes=collections.defaultdict(list)
        res=0
        for k,v in edges:
            routes[k].append(v)
            routes[v].append(k)
            
        res=self.solve(routes,hasApple,0,0)
        return res

参考文献

[LeetCode] [Python] Beats 100% Short DFS Easy to Read

猜你喜欢

转载自blog.csdn.net/w5688414/article/details/109323764