1.问题描述
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.【假设你有一个很长的花圃,其中有些地是种植的,有些不是。然而,鲜花不能种植在相邻的地块上——它们会争夺水,两者都会死亡。给定一个花坛(表示为包含0和1的数组,其中0表示为空,1表示不为空)和一个数字n,如果可以在不违反无邻接花规则的情况下在花坛中种植n个新花,则返回。】
2.输入
[1,0,0,0,1] 1
[1,0,0,0,1] 2
3.输出
true
false
4.代码
从控制台读取输入,读入的数据为字符串,需要预处理。
用一个mask矩阵记录当前flowerbed的位置是否能种植新的花朵。
每种植一新的花朵,就更新mask
若count>=target print :true
if __name__ == "__main__": def update_mask(mask,flowerbed): for idx in range(len(flowerbed)): if len(flowerbed)==1: mask[idx]=False if flowerbed[idx]=='1' else True elif len(flowerbed)==2: if idx==0 and flowerbed[idx]=='1': mask[idx]=False mask[idx+1]=False if idx==1 and flowerbed[idx]=='1': mask[idx-1] = False mask[idx] = False elif len(flowerbed) >= 3: if idx==0 and flowerbed[idx]=='1': mask[idx]=False mask[idx+1]=False elif idx==len(flowerbed)-1 and flowerbed[idx]=='1': mask[idx - 1] = False mask[idx] = False elif flowerbed[idx]=='1': mask[idx - 1] = False mask[idx] = False mask[idx+1]=False return mask while True: data = input() list_data = data[1:-3] target = int(data[-1]) flowerbed = list_data.split(',') mask = [True]*len(flowerbed) mask = update_mask(mask, flowerbed) # 已经得到了mask # 开始插花 count = 0 for idx in range(len(mask)): if mask[idx]==True: flowerbed[idx]='1' count += 1 mask=update_mask(mask,flowerbed) if count>=target: print('true') else: print('false')