Plant Flowers Without Adjacency
Problem
You have a row of flower beds where each bed is empty (0) or already planted (1). No two flowers may sit in adjacent beds. Decide whether n additional flowers can be planted. Walk left to right, planting greedily wherever the bed and both neighbours are empty.
Input
bed = [1, 0, 0, 0, 1], n = 1Output
truePlant in position 2: result becomes [1, 0, 1, 0, 1].
def can_place(bed, n):
i = 0
while i < len(bed) and n > 0:
if bed[i] == 0 \
and (i == 0 or bed[i - 1] == 0) \
and (i == len(bed) - 1 or bed[i + 1] == 0):
bed[i] = 1; n -= 1
i += 1
return n == 0
function canPlace(bed, n) {
for (let i = 0; i < bed.length && n > 0; i++) {
if (bed[i] === 0
&& (i === 0 || bed[i - 1] === 0)
&& (i === bed.length - 1 || bed[i + 1] === 0)) {
bed[i] = 1; n--;
}
}
return n === 0;
}
class Solution {
public boolean canPlace(int[] bed, int n) {
for (int i = 0; i < bed.length && n > 0; i++) {
if (bed[i] == 0
&& (i == 0 || bed[i - 1] == 0)
&& (i == bed.length - 1 || bed[i + 1] == 0)) {
bed[i] = 1; n--;
}
}
return n == 0;
}
}
bool canPlace(vector<int>& bed, int n) {
for (int i = 0; i < (int)bed.size() && n > 0; i++) {
if (bed[i] == 0
&& (i == 0 || bed[i - 1] == 0)
&& (i == (int)bed.size() - 1 || bed[i + 1] == 0)) {
bed[i] = 1; n--;
}
}
return n == 0;
}