你能从盒子里获得的最大糖果数

标签: 广度优先搜索 数组

难度: Hard

给你 n 个盒子,每个盒子的格式为 [status, candies, keys, containedBoxes] ,其中:

  • 状态字 status[i]:整数,如果 box[i] 是开的,那么是 ,否则是
  • 糖果数 candies[i]: 整数,表示 box[i] 中糖果的数目。
  • 钥匙 keys[i]:数组,表示你打开 box[i] 后,可以得到一些盒子的钥匙,每个元素分别为该钥匙对应盒子的下标。
  • 内含的盒子 containedBoxes[i]:整数,表示放在 box[i] 里的盒子所对应的下标。

给你一个 initialBoxes 数组,表示你现在得到的盒子,你可以获得里面的糖果,也可以用盒子里的钥匙打开新的盒子,还可以继续探索从这个盒子里找到的其他盒子。

请你按照上述规则,返回可以获得糖果的 最大数目 

示例 1:

输入:status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]
输出:16
解释:
一开始你有盒子 0 。你将获得它里面的 7 个糖果和盒子 1 和 2。
盒子 1 目前状态是关闭的,而且你还没有对应它的钥匙。所以你将会打开盒子 2 ,并得到里面的 4 个糖果和盒子 1 的钥匙。
在盒子 1 中,你会获得 5 个糖果和盒子 3 ,但是你没法获得盒子 3 的钥匙所以盒子 3 会保持关闭状态。
你总共可以获得的糖果数目 = 7 + 4 + 5 = 16 个。

示例 2:

输入:status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]
输出:6
解释:
你一开始拥有盒子 0 。打开它你可以找到盒子 1,2,3,4,5 和它们对应的钥匙。
打开这些盒子,你将获得所有盒子的糖果,所以总糖果数为 6 个。

示例 3:

输入:status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1]
输出:1

示例 4:

输入:status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = []
输出:0

示例 5:

输入:status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0]
输出:7

提示:

  • 1 <= status.length <= 1000
  • status.length == candies.length == keys.length == containedBoxes.length == n
  • status[i] 要么是 0 要么是 1
  • 1 <= candies[i] <= 1000
  • 0 <= keys[i].length <= status.length
  • 0 <= keys[i][j] < status.length
  • keys[i] 中的值都是互不相同的。
  • 0 <= containedBoxes[i].length <= status.length
  • 0 <= containedBoxes[i][j] < status.length
  • containedBoxes[i] 中的值都是互不相同的。
  • 每个盒子最多被一个盒子包含。
  • 0 <= initialBoxes.length <= status.length
  • 0 <= initialBoxes[i] < status.length

Submission

运行时间: 59 ms

内存: 26.1 MB

class Solution:
    def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:
        n = len(status)
        can_open = [status[i] == 1 for i in range(n)]
        has_box, used = [False] * n, [False] * n
        
        q = collections.deque()
        ans = 0
        for box in initialBoxes:
            has_box[box] = True
            if can_open[box]:
                q.append(box)
                used[box] = True
                ans += candies[box]
        
        while len(q) > 0:
            big_box = q.popleft()
            for key in keys[big_box]:
                can_open[key] = True
                if not used[key] and has_box[key]:
                    q.append(key)
                    used[key] = True
                    ans += candies[key]
            for box in containedBoxes[big_box]:
                has_box[box] = True
                if not used[box] and can_open[box]:
                    q.append(box)
                    used[box] = True
                    ans += candies[box]
        
        return ans

Explain

此题解采用广度优先搜索(BFS)策略来解决问题。首先,我们初始化一些基本数据结构:can_open数组用于标记每个盒子是否可以打开,has_box数组用于标记我们是否拥有某个盒子,used数组用于标记盒子是否已被处理过。将初始盒子加入队列q,并更新对应的状态。随后,从队列中逐个取出盒子,收集糖果,使用钥匙尝试打开新盒子,并将新发现的盒子加入队列。此过程持续进行直到队列为空,此时,所有可以通过当前条件打开的盒子都已处理完毕。

时间复杂度: O(n)

空间复杂度: O(n)

# This class defines the solution to the problem using BFS strategy.

class Solution:
    def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:
        n = len(status)
        # Track if a box can be opened
        can_open = [status[i] == 1 for i in range(n)]
        # Track if a box is possessed and if it's been used
        has_box, used = [False] * n, [False] * n

        q = collections.deque()
        ans = 0
        # Process initial boxes
        for box in initialBoxes:
            has_box[box] = True
            if can_open[box]:
                q.append(box)
                used[box] = True
                ans += candies[box]

        # Continue processing as long as there are boxes in the queue
        while len(q) > 0:
            big_box = q.popleft()
            # Use keys from the current box to open other boxes
            for key in keys[big_box]:
                can_open[key] = True
                if not used[key] and has_box[key]:
                    q.append(key)
                    used[key] = True
                    ans += candies[key]
            # Process newly contained boxes
            for box in containedBoxes[big_box]:
                has_box[box] = True
                if not used[box] and can_open[box]:
                    q.append(box)
                    used[box] = True
                    ans += candies[box]

        return ans

Explore

在此问题中,广度优先搜索(BFS)被选择是因为它按层次处理每个盒子和相关的钥匙,这样可以更快地解锁新盒子并访问更多的糖果。相比之下,深度优先搜索(DFS)可能会导致算法深入到一个分支,延迟发现其他可立即打开的盒子。BFS确保一旦获得新的钥匙或盒子,就能尽快处理,从而更有效率地最大化糖果的收集。

used数组在算法中用于标记一个盒子是否已经被处理过。这是必须的,因为一个盒子可能多次成为处理的候选(例如,通过不同的钥匙或者直接拥有),而我们需要确保每个盒子只被处理一次以避免重复操作和潜在的无限循环。此外,这也帮助算法保持高效,减少不必要的重复处理,从而优化性能。

检查钥匙对应的盒子是否已经拥有并且未使用过是为了确保我们不遗漏任何可以立即打开的盒子。这种检查可以防止算法浪费资源去尝试打开一个已经在处理中或已处理的盒子,同时也确保所有获取的钥匙都被有效利用。这种策略提高了算法的效率,因为它减少了不必要的队列操作和重复检查,使算法能够集中处理那些确实可以带来新糖果和新机会的盒子。

在此BFS算法实现中,并没有特定的规则来决定多个可打开盒子的处理顺序;它们是按照它们被发现和加入队列的顺序处理的。由于问题的性质,处理不同盒子的顺序并不影响最终可以获得的糖果总数,只要所有可通过当前钥匙打开的盒子最终都被处理。这意味着无论处理顺序如何,只要遍历完所有的可能性,收集到的糖果总数都是相同的。