You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed
containing 0
's and 1
's, where 0
means empty and 1
means not empty, and an integer n
, return if n
new flowers can be planted in the flowerbed
without violating the no-adjacent-flowers rule.
Example 1:
Input: flowerbed = [1,0,0,0,1,0,0,0,1], n = 2
Output: Given all flowers can be place
Example 2:
Input: flowerbed =[1,0,0,0,1,0,0,0,1], n = 3
Output: Given all flowers can not be place
Approach
Java
public class CanPlaceFlowers {public static void main(String[] args) {int flowerbed[] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 };int n = 3;if (canPlaceFlowers(flowerbed, n)) {System.out.println("Given all flowers can be place");} else {System.out.println("Given all flowers can not be place");}}public static boolean canPlaceFlowers(int[] flowerbed, int n) {int prev = 0;for (int i = 0; i < flowerbed.length; i++) {if (n > 0) {int next = 0;if (i < flowerbed.length - 1) {next = flowerbed[i + 1];}if (prev == 0 && flowerbed[i] == 0 && next == 0) {n--;prev++;flowerbed[i] = 1;}prev = flowerbed[i];}}if (n == 0)return true;elsereturn false;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check that we//can place the flowers such that no//two flowers are adjacentbool canPlaceFlowers(int flowerbed[], int n,int m){//count the no of current placed flowerint cnt=0;int flag=0;//if their is no flower to put//return trueif(n==0)return true;//if only one element and only//one flower to put then return true//if flowerbed[0]=0if(m==1&&n==1&&flowerbed[0]==0)return true;//iterate for all the indexfor(int i=0;i<m;i++){//if we are at first positionif(i==0){//if first is empty and second also empty//the increment cnt and make flowerbed[i]=1if(flowerbed[i]==0&&i+1<m&&flowerbed[i+1]==0){cnt++;flowerbed[i]=1;}}//if we are at the last position of the array//if second last is empty and last is empty//increment the count ans make the last as 1else if(i==m-1){if(i-1>=0&&flowerbed[i-1]==0&&flowerbed[i]==0){cnt++;flowerbed[i]=1;}}//else we check left of position and right of positionelse{//if left ,right and current index is 0 then//increment the count and make the current index as 1if(flowerbed[i]==0&&flowerbed[i-1]==0&&flowerbed[i+1]==0){cnt++;flowerbed[i]=1;}}//if count becomes n break out of loop//and make flag as 1if(cnt==n){flag=1;break;}}//if flag remain 0 then return falseif(flag==0)return false;//else return trueelsereturn true;}int main(){int flowerbed[]={1,0,0,0,1,0,0,0,1};int n=3;int m=sizeof(flowerbed)/sizeof(flowerbed[0]);if(canPlaceFlowers(flowerbed,n,m))cout<<"Given all flower can be place\n";elsecout<<"Given all flowers can not be place\n";return 0;}
No comments:
Post a Comment