# C#LeetCode刷题之#605-种花问题（ Can Place Flowers）

n 是非负整数，且不会超过输入数组的大小。

Suppose 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 – they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.

Input: flowerbed = [1,0,0,0,1], n = 1

Output: True

Input: flowerbed = [1,0,0,0,1], n = 2

Output: False

Note:

The input array won’t violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won’t exceed the input array size.

```public class Program {

public static void Main(string[] args) {
int[] nums = null;

nums = new int[] { 1, 0, 0, 0, 1 };
var res = CanPlaceFlowers(nums, 1);
Console.WriteLine(res);

}

private static bool CanPlaceFlowers(int[] flowerbed, int n) {
//该题比较简单，处理好边界即可
//需要种植的花为0，总是可以
if(n == 0) return true;
//数组为0，不可种植
if(flowerbed.Length == 0) {
return false;
}
//当数组为1时，根据是否种植直接判定即可
if(flowerbed.Length == 1) {
if(flowerbed[0] == 0) {
return true;
} else {
return false;
}
}
//记录可以种植的数量
int count = 0;
//前2个分析
if(flowerbed.Length >= 2 &&
flowerbed[0] == 0 &&
flowerbed[1] == 0) {
flowerbed[0] = 1;
count++;
}
//连续3个为0时，可种植
for(int i = 1; i < flowerbed.Length - 1; i++) {
if(flowerbed[i - 1] == 0 &&
flowerbed[i] == 0 &&
flowerbed[i + 1] == 0) {
count++;
flowerbed[i] = 1;
}
}
//后2个分析
if(flowerbed.Length >= 2 &&
flowerbed[flowerbed.Length - 1] == 0 &&
flowerbed[flowerbed.Length - 2] == 0) {
flowerbed[flowerbed.Length - 1] = 1;
count++;
}
//可种植数大于等于即将种植的数量时，返回true
if(count >= n) return true;
//无解时，返回false
return false;
}

}```

`True`

(2)