过河问题
一个猎人要带着一棵胡萝卜,一只狗,一头羊,两只老虎过河.现在小船有三个座位,猎人最多带两样东西过河,没有人和狗在,老虎会吃了羊,狗和羊单独在一起会吵架,羊和胡萝卜单独在一起会吃掉胡萝卜,有什么办法一起过河?
My Code
visited = []
class State:
def __init__(self,tuple,prev=None):
self.tuple = tuple#猎人,胡萝卜,羊,狗,老虎2
self.prev = prev
def bfs(state):
queue = []
s = state
queue.append(s)
visited.append(s.tuple)
while queue:
prev = queue.pop(0)
state = prev.tuple
states = []
delete = []
if state[0] == 1:
a,b,c,d,e = state
states.append([a-1,b-1,c-1,d,e])
states.append([a-1,b-1,c,d-1,e])
states.append([a-1,b-1,c,d,e-1])
states.append([a-1,b,c-1,d-1,e])
states.append([a-1,b,c-1,d,e-1])
states.append([a-1,b,c,d-1,e-1])
states.append([a-1,b,c,d,e-2])
states.append([a - 1, b, c, d, e])
states.append([a - 1, b - 1, c, d, e])
states.append([a - 1, b, c - 1, d, e])
states.append([a - 1, b, c, d - 1, e])
states.append([a - 1, b, c, d, e - 1])
if state[0] == 0:
a,b,c,d,e = state
states.append([a+1,b+1,c+1,d,e])
states.append([a+1,b+1,c,d+1,e])
states.append([a+1,b+1,c,d,e+1])
states.append([a+1,b,c+1,d+1,e])
states.append([a+1,b,c+1,d,e+1])
states.append([a+1,b,c,d+1,e+1])
states.append([a+1,b,c,d,e+2])
states.append([a+1, b, c, d, e])
states.append([a+1, b+1, c, d, e])
states.append([a+1, b, c+1, d, e])
states.append([a+1, b, c, d+1, e])
states.append([a+1, b, c, d, e+1])
for state in states:
if -1 in state or -2 in state:
delete.append(state)
if state[0] >1 or state[1] > 1 or state[2]>1 or state[3]>1or state[4]> 2:
delete.append(state)
if state[0] == 0 and state[3] == 0 and state[2] == 1 and state[4] > 0:
if state in delete:
continue
else:
delete.append(state)
continue
if state[0] == 1 and state[3] == 1 and state[2] == 0 and state[4] <= 1:
if state in delete:
continue
else:
delete.append(state)
continue
if state[3] == 1 and state[2] == 1 and state[0] == 0 and state[4] == 0 and state[1] == 0:
if state in delete:
continue
else:
delete.append(state)
continue
if state[3] == 0 and state[2] == 0 and state[0] == 1 and state[4] == 2 and state[1] == 1:
if state in delete:
continue
else:
delete.append(state)
continue
if state[1] == 0 and state[2] == 0 and state[0] == 1 and state[3] == 1 :
if state in delete:
continue
else:
delete.append(state)
continue
if state[1] == 1 and state[2] == 1 and state[0] == 0 and state[3] == 0 :
if state in delete:
continue
else:
delete.append(state)
continue
for i in delete:
states.remove(i)
for state in states:
if state in visited:
continue
else:
new_state = State(state,prev=prev)
queue.append(new_state)
visited.append(new_state.tuple)
if state == [0,0,0,0,0]:
print('Ok!')
return new_state
return None
def path(state):
path = []
while state.prev:
path.append(state.tuple)
state = state.prev
return path[::-1]
left_init = State([1,1,1,1,2],prev=None)
result = bfs(left_init)
path = path(result)
print('共运送了'+str(len(path))+'次')
for i in path:
print(i)