Skip to content

Commit 0cf059d

Browse files
committed
feat: add question 1298
1 parent bbcfae1 commit 0cf059d

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* @lc app=leetcode.cn id=1298 lang=javascript
3+
*
4+
* [1298] 你能从盒子里获得的最大糖果数
5+
*
6+
* 1. 没什么算法, 模拟过程即可
7+
* 2. 详细逻辑看注释
8+
*/
9+
10+
// @lc code=start
11+
/**
12+
* @param {number[]} status
13+
* @param {number[]} candies
14+
* @param {number[][]} keys
15+
* @param {number[][]} containedBoxes
16+
* @param {number[]} initialBoxes
17+
* @return {number}
18+
*/
19+
var maxCandies = function(status, candies, keys, containedBoxes, initialBoxes) {
20+
const set = new Set(); // 已经处理过的盒子
21+
const key = new Set(); // 手上的钥匙
22+
const boxs = initialBoxes; // 待处理盒子队列
23+
const lockBoxs = []; // 待处理上锁的盒子
24+
let result = 0;
25+
26+
while (boxs.length > 0) {
27+
const box = boxs.shift();
28+
29+
// 如果当前盒子是锁着的, 而且没有钥匙, 则加入到"待处理上锁的盒子"
30+
if (status[box] === 0 && !key.has(box)) {
31+
lockBoxs.push(box);
32+
continue;
33+
}
34+
35+
// 处理当前盒子
36+
set.add(box);
37+
key.delete(box);
38+
result += candies[box];
39+
// 所持钥匙加到"手上钥匙"
40+
keys[box].forEach(x => {
41+
key.add(x);
42+
})
43+
// 包含盒子加到队列
44+
containedBoxes[box].forEach(x => {
45+
if (!set.has(x)) {
46+
boxs.push(x);
47+
}
48+
})
49+
50+
// 如果队列空了, 并且有上锁盒子, 并且还有钥匙, 则把上锁盒子推到队列中
51+
if (boxs.length === 0 && lockBoxs.length && key.size) {
52+
while (lockBoxs.length) {
53+
boxs.push(lockBoxs.pop());
54+
}
55+
}
56+
}
57+
58+
return result;
59+
};
60+
// @lc code=end

0 commit comments

Comments
 (0)