Advertisement
nikunjsoni

1298

Apr 26th, 2021
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int maxCandies(vector<int>& status, vector<int>& candies, vector<vector<int>>& keys, vector<vector<int>>& containedBoxes, vector<int>& initialBoxes) {
  4.         vector<bool> explored(status.size(), false);
  5.         vector<bool> visited(status.size(), false);
  6.         int ans = 0;
  7.         queue<int> q;
  8.        
  9.         // Input the starting boxes in queue.
  10.         for(int box: initialBoxes){
  11.             if(status[box]){
  12.                 q.push(box);
  13.                 visited[box] = true;
  14.             }
  15.             else
  16.                 explored[box] = true;
  17.         }
  18.        
  19.         // Pop from queue and input next boxes in queue.
  20.         while(!q.empty()){
  21.             int box = q.front(); q.pop();
  22.             ans += candies[box];
  23.             // Input boxes which are explored and their keys are found.
  24.             for(int key: keys[box]){
  25.                 status[key] = 1;
  26.                 if(explored[key] && !visited[key]){
  27.                     q.push(key);
  28.                     visited[key] = true;
  29.                 }
  30.             }
  31.             // Input or explored next boxes based on keys.
  32.             for(int nextBox: containedBoxes[box]){
  33.                 if(status[nextBox] && !visited[nextBox]){
  34.                     q.push(nextBox);
  35.                     visited[nextBox] = true;
  36.                 }
  37.                 else
  38.                     explored[nextBox] = true;
  39.             }
  40.         }
  41.         return ans;
  42.     }
  43. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement