Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SuryaPratapK/d3c3033e1db7c108add316a20b90156e to your computer and use it in GitHub Desktop.
Save SuryaPratapK/d3c3033e1db7c108add316a20b90156e to your computer and use it in GitHub Desktop.
class Solution {
public:
int maxCandies(vector<int>& status, vector<int>& candies, vector<vector<int>>& keys, vector<vector<int>>& containedBoxes, vector<int>& initialBoxes) {
int n=status.size();
//Apply BFS from start points: Multi-Source BFS (DAG: Since Box-A inside Box-B then opposite is NOT True)
queue<int> q;
for(int start: initialBoxes)
q.push(start);
unordered_set<int> closed;
int total = 0;
while(!q.empty()){
int curr = q.front();
q.pop();
//If current box is closed then save it for possible later opening (by finding key)
if(status[curr]==0){
closed.insert(curr);
continue;
}
//Current box is open. Let's open the closed boxes (if any)
for(int open: keys[curr]){
status[open]=1;
if(closed.count(open)){
q.push(open);
closed.erase(open);
}
}
//Add value and store adjacent nodes
total += candies[curr];
for(int nbr: containedBoxes[curr])
q.push(nbr);
}
return total;
}
};
/*
//JAVA
import java.util.*;
class Solution {
public int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) {
int n = status.length;
Queue<Integer> q = new LinkedList<>();
for (int start : initialBoxes) {
q.offer(start);
}
Set<Integer> closed = new HashSet<>();
int total = 0;
while (!q.isEmpty()) {
int curr = q.poll();
if (status[curr] == 0) {
closed.add(curr);
continue;
}
for (int open : keys[curr]) {
status[open] = 1;
if (closed.contains(open)) {
q.offer(open);
closed.remove(open);
}
}
total += candies[curr];
for (int nbr : containedBoxes[curr]) {
q.offer(nbr);
}
}
return total;
}
}
#Python
from collections import deque
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)
q = deque(initialBoxes)
closed = set()
total = 0
while q:
curr = q.popleft()
if status[curr] == 0:
closed.add(curr)
continue
for open in keys[curr]:
status[open] = 1
if open in closed:
q.append(open)
closed.remove(open)
total += candies[curr]
for nbr in containedBoxes[curr]:
q.append(nbr)
return total
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment