1298 - Maximum Candies You Can Get from Boxes
info
- 문제 보기: 1298 - Maximum Candies You Can Get from Boxes
- 소요 시간: 35분 6초
- 풀이 언어:
java
- 체감 난이도: 3️⃣
- 리뷰 횟수: ✅
풀이 키워드
스포주의
bfs
구현
풀이 코드
info
- 메모리: 57020 KB
- 시간: 3 ms
class Solution {
public int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) {
boolean[] visited = new boolean[status.length];
boolean[] haveKey = new boolean[status.length];
// init
Deque<Integer> q = new ArrayDeque<>();
for (int i : initialBoxes) {
q.add(i);
visited[i] = true;
for (int j : keys[i]) haveKey[j] = true;
}
// break condition: found no key & box == hopeless
boolean hope = true;
int ans = 0;
while (hope) {
int sz = q.size();
hope = false;
while (sz-- > 0) {
int i = q.poll();
if (status[i] == 1 || (status[i] == 0 && haveKey[i])) { // 1. opened or can open
for (int k : keys[i]) {
if (haveKey[k]) continue; // useless key
haveKey[k] = true; // get keys
hope = true;
}
for (int b : containedBoxes[i]) {
if (visited[b]) continue;
q.add(b); // get boxes
visited[b] = true;
hope = true;
}
ans += candies[i];
}
else { // 2. closed or can't open
q.add(i);
}
}
}
return ans;
}
}
풀이 해설
지문의 내용에 따라 그대로 조건을 구현해서 bfs로 풀이하는 문제이다.