C++ code to check all bulbs can be turned on or not


Suppose we have a number m and a nested list A with n sub-lists. Consider there are m bulbs, initially all are turned off. There are n buttons and each of them is connected to some set of bulbs. So A[i] is the set of bulbs that can be turned on by pressing ith switch. We have to check whether we can lit up all the bulbs or not.

So, if the input is like A = [[1, 4], [1, 3, 1], [2]]; m = 4, then the output will be True, because by pressing all switches we can turn on all four bulbs.

Steps

To solve this, we will follow these steps −

Define one set s
for initialize i := 0, when i < size of A, update (increase i by 1), do:
   for initialize j := 0, when j < size of A[i], update (increase j by 1), do:
      insert A[i, j] into s
if size of s is same as m, then:
   return true
Otherwise
   return false

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
bool solve(vector<vector<int>> A, int m){
   set<int> s;
   for (int i = 0; i < A.size(); i++){
      for (int j = 0; j < A[i].size(); j++){
         s.insert(A[i][j]);
      }
   }
   if (s.size() == m)
      return true;
   else
      return false;
}
int main(){
   vector<vector<int>> A = { { 1, 4 }, { 1, 3, 1 }, { 2 } };
   int m = 4;
   cout <<solve(A, m) << endl;
}

Input

{ { 1, 4 }, { 1, 3, 1 }, { 2 } }, 4

Output

1

Updated on: 15-Mar-2022

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements