Likou Flower Planting Issue on January 1

As the title

Suppose there is a very long flower bed, and one part of the plot is planted with flowers, but the other part is not. However, flowers cannot be planted on adjacent plots. They will compete for water and both will die.
Give you an integer array flowerbed that represents a flowerbed, which is composed of a number of 0 and 1, where 0 means no flowers are planted, and 1 means flowers are planted. There is also a number n. Can n flowers be planted without breaking the planting rules? It returns true if it can, and false if it can't.

Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true

Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false

First of all, we can think of four methods if there is only one pit at the beginning. (See programming.)
Then look directly at the back. If the last and penultimate are both zero, that is, if there are holes, the last one can also be used for planting flowers. The number of flowers +1 is
in the middle, and the number in the middle can be calculated by traversal. If the three numbers are all zero, then the number in the middle can definitely be used to grow flowers, and the number of flowers is +1.
In general, it is the programming below.

bool canPlaceFlowers(int* flowerbed, int flowerbedSize, int n){
    
    
    int i,a = 0;
    if(flowerbedSize == 1){
    
    
        if(flowerbed[0]==0&&n==1){
    
    	
            return true;
        }
         if(flowerbed[0]==1&&n==1){
    
    
            return false;
        }
         if(flowerbed[0]==0&&n==0){
    
    
            return true;
        }
         if(flowerbed[0]==1&&n==0){
    
    
            return true;//前四种方法应该都能看懂,就是数学方法。
        }//用数学方法来看如果只有一个的话是怎么样的。
    }
    if(flowerbed[0]==0&&flowerbed[1]==0){
    
    
        flowerbed[0]=1;
        a++;
    }
    if(flowerbed[flowerbedSize-1]==0&&flowerbed[flowerbedSize-2]==0){
    
    
        flowerbed[flowerbedSize-1]=1;
        a++;//这个是最后一个。
    }
    for(i = 1;i<flowerbedSize-1;i++){
    
    //再把中间的数全部遍历一遍,就完事了。
        if(flowerbed[i]==0&&flowerbed[i-1]==0&&flowerbed[i+1]==0){
    
    
            flowerbed[i] = 1;
            a++;
        }
    }
    return a >=n;//如果最后a>=n,返回1,true,反之返回false
}

Guess you like

Origin blog.csdn.net/FG_future/article/details/112124210