1298. Maximum Candies You Can Get from Boxes
https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/
Given n
boxes, each box is given in the format [status, candies, keys, containedBoxes]
where:
status[i]
: an integer which is 1 ifbox[i]
is open and 0 ifbox[i]
is closed.candies[i]
: an integer representing the number of candies inbox[i]
.keys[i]
: an array contains the indices of the boxes you can open with the key inbox[i]
.containedBoxes[i]
: an array contains the indices of the boxes found inbox[i]
.
You will start with some boxes given in initialBoxes
array. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.
Return the maximum number of candies you can get following the rules above.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Constraints:
1 <= status.length <= 1000
status.length == candies.length == keys.length == containedBoxes.length == n
status[i]
is0
or1
.1 <= candies[i] <= 1000
0 <= keys[i].length <= status.length
0 <= keys[i][j] < status.length
All values in
keys[i]
are unique.0 <= containedBoxes[i].length <= status.length
0 <= containedBoxes[i][j] < status.length
All values in
containedBoxes[i]
are unique.Each box is contained in one box at most.
0 <= initialBoxes.length <= status.length
0 <= initialBoxes[i] < status.length
有一堆盒子,盒子是开或关的(status),每打开一个盒子,可能获得其它盒子(containedBoxes)和其它盒子的钥匙(keys)以及一定量的糖(candies),初始手里有一些盒子(initialBoxes),问通过这些盒子最后最多能拿多少糖。最难的地方就是理解题目意思了,本质是个BFS,initialBoxes为q的初始状态,每次通过拿糖,开箱,开锁后更新手里的盒子作为BFS的新一层。BFS时手里打不开的盒子继续拿在手里,放到新层;取走糖后candies对应元素要置零,以防盒子里又套回曾经的盒子的“套娃”情况。当本层操作后手里没有新盒子时,BFS结束。
Last updated
Was this helpful?