How to planted in adjacent plots – Place Flowers in C++ ?

  C & C ++ Interview Q&A

Dear readers, today read in this article how to plant in adjacent plots – Place flowers in C ++?

If you have a tall flower with some plots planted and some empty. Now there is a hitch, flowers cannot be planted in the surrounding plots, they will compete for water and both will die. So if we have a flower, which is represented by an array containing 0 and 1, 0, indicates empty and fills 1, and a number n is also given, we have to check if there is any violation New flowers can be planted in K n- adjacent-flower rule or not.

Therefore, if the input is flower-like = [1,0,0,0,1], n = 1, then the output will be true

Example for Place flowers in C++

#include <bits/stdc++.h>
using namespace std;
class placeFlowerProg{
public:
   bool canPlaceFlowers(vector<int>& flowerbed, int n) {
      if (flowerbed.size() < n)
         return false;
      if (flowerbed.size() == 1 && flowerbed[0] == 0 && n == 1)
         return true;
      for (int i = 0; i < flowerbed.size(); i++) {
         if (n > 0) {
            if (i == 0) {
               if (flowerbed[i] == 0 && flowerbed[1] == 0) {
                  flowerbed[0] = 1;
                  n--;
               }
            }
            else if (i == flowerbed.size() - 1) {
               if (flowerbed[i] == 0 && flowerbed[i - 1] != 1) {
                  flowerbed[i] = 1;
                  n--;
               }
            }
            else if (flowerbed[i] == 0 && flowerbed[i + 1] == 0 && flowerbed[i - 1] == 0) {
flowerbed[i] = 1;
               n--;
            }
         }
         if (n == 0) {
            return true;
         }
      }
      if (n == 0) {
         return true;
      }
      return false;
   }
};
main(){
   placeFlowerProg ob;
   vector<int> v = {1,0,0,0,1};
   cout << (ob.canPlaceFlowers(v, 1));
}

Output

1

LEAVE A COMMENT