一个农夫在河的西岸带了一匹狼、一只羊和一棵白菜,他需要把这三样东西用船带到河的东岸。然而,这艘船只能容下农夫本人和另外一样东西。如果农夫不在场的话,狼会吃掉羊,羊也会吃掉白菜。
w = [1, 2, 3] # 西岸初始状态 0代表没有 1代表白菜 2代表羊 3代表狼
e = [0] * 3 # 东岸初始状态
li = [] # 储存每一次所带的东西
cnt = 0 # 记录农夫所在位置,单数代表西岸,双数代表东岸
条件处理一:农夫不在的一侧,不能同时存在狼和羊,羊和白菜。条件不成立则重新开始。
if cnt % 2 == 1 and (3 in w and 2 in w or 2 in w and 1 in w)
\or cnt % 2 == 0 and (3 in e and 2 in e or 2 in e and 1 in e):
w = [1, 2, 3]
e = [0] * 3
li = []
cnt = 0
条件处理二:m代表所带东西索引,-1则啥也不带。
如果当m != -1且农夫所在一侧m所对东西存在(即元素不为0),则农夫带该东西过河。
否则农夫啥也不带过河。
m = random.randint(-1, 2)
li.append(m)
if m != -1 and w[m] != 0 and cnt % 2 == 0:
w[m], e[m] = e[m], w[m] # 带过河即交换两岸物品列表元素
elif m != -1 and e[m] != 0 and cnt % 2 == 1:
w[m], e[m] = e[m], w[m]
else:
li[-1] = -1
当所有狼羊白菜均带过去,则跳出循环。 得到步骤列表,再处理列表,打印最终步骤。
全部代码:
import random
w = [1, 2, 3] # 西岸初始状态 0代表没有 1代表白菜 2代表羊 3代表狼
e = [0] * 3 # 东岸初始状态
li = [] # 储存每一步所带的东西
cnt = 0 # 记录农夫所在位置,单数代表西岸,双数代表东岸
while True:
if cnt % 2 == 1 and (3 in w and 2 in w or 2 in w and 1 in w) \
or cnt % 2 == 0 and (3 in e and 2 in e or 2 in e and 1 in e):
w = [1, 2, 3]
e = [0] * 3
li = []
cnt = 0
continue
m = random.randint(-1, 2)
li.append(m)
if m != -1 and w[m] != 0 and cnt % 2 == 0:
w[m], e[m] = e[m], w[m] # 带过河即交换两岸物品列表元素
elif m != -1 and e[m] != 0 and cnt % 2 == 1:
w[m], e[m] = e[m], w[m]
else:
li[-1] = -1
if e == [1, 2, 3]:
break
cnt += 1
lit = ['啥也不带', '蔬菜', '羊', '狼']
for i in range(len(li)-1): # 去除无效步骤
if li[i] == li[i+1]:
li[i] = li[i+1] = []
while [] in li:
li.remove([])
for i in li: # 打印最终步骤
print(lit[i+1], end='\t')