Can Place Flowers in C++


Suppose we have a long flowerbed in which some of the plots are planted and some are empty. Now there is a constraint, flowers cannot be planted in adjacent plots, they would compete for water and both would die. So if we have a flowerbed, represented by an array containing 0 and 1, 0 indicates empty and 1 indicates fill, and a number n is also given, we have to check whether n new flowers can be planted in it without violating the no-adjacent-flowers rule or not.

So, if the input is like flowerbed = [1,0,0,0,1], n = 1, then the output will be True

To solve this, we will follow these steps −

  • if the size of flowerbed < n, then −

    • return false

  • if size of flowerbed is same as 1 and flowerbed[0] is same as 0 and n is same as 1, then −

    • return true

  • for initialize i := 0, when i < size of flowerbed, update (increase i by 1), do −

    • if n > 0, then −

      • if i is same as 0, then −

        • if flowerbed[i] is same as 0 and flowerbed[1] is same as 0, then −

          • flowerbed[0] := 1

          • (decrease n by 1)

      • otherwise when i is same as size of flowerbed - 1, then −

        • if flowerbed[i] is same as 0 and flowerbed[i - 1] is not equal to 1, then −

          • flowerbed[i] := 1

          • (decrease n by 1)

      • otherwise when flowerbed[i] is same as 0 and flowerbed[i + 1] is same as 0 and flowerbed[i - 1] is same as 0, then −

        • flowerbed[i] := 1

        • (decrease n by 1)

    • if n is same as 0, then −

      • return true

  • if n is same as 0, then −

    • return true

  • return false

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
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(){
   Solution ob;
   vector<int> v = {1,0,0,0,1};
   cout << (ob.canPlaceFlowers(v, 1));
}

Input

{1,0,0,0,1}, 1

Output

1

Updated on: 11-Jun-2020

759 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements