'''
问题描述:三个野人,三个传教士,一艘船,船上至多有两人,在一起的野人数不能超过传教士,否则传教士被吃。
状态=[传教士数,野人数,船是否在本岸]
动作=[传教士上船人数,野人上船人数]
变量说明:
*state_route:[[state],[action1],[action2]] 用以描述当前state,是经过怎样的动作序列得到。
*state_table: [state_route, stateroute...] 未探索的状态及路径列表
*searched_table:[state,state...] 已探索的状态列表
'''
def state_transfer(state_route, action):
route = state_route.copy()
state = route[0]
new_state = [0, 0, 0]
if state[2] == 1:
if state[0] < action[0] or state[1] < action[1]:
return False
else:
new_state[0] = state[0]-action[0]
new_state[1] = state[1]-action[1]
new_state[2] = 1-state[2]
else:
if 3-state[0] < action[0] or 3-state[1] < action[1]:
return False
else:
new_state[0] = state[0]+action[0]
new_state[1] = state[1]+action[1]
new_state[2] = 1-state[2]
if new_state[0] < new_state[1] and new_state[0] != 0:
return False
if 3-new_state[0] < 3-new_state[1] and 3-new_state[0] != 0:
return False
route[0] = new_state
route.append(action)
return route
def main():
state_table = []
state_route = []
target = [0,0,0]
state_init = [3, 3, 1]
state_route.append(state_init.copy())
state_table.append(state_route.copy())
searched_table = []
action = [[0,1],[1,0],[0,2],[2,0],[1,1]]
while state_table != []:
if state_table[0][0] not in searched_table:
for i in range(5):
state_route = state_transfer(state_table[0], action[i])
if state_route is False:
continue
if state_route[0] == target:
print(state_route)
break
state_table.append(state_route)
searched_table.append(state_table[0][0])
state_table.pop(0)
if __name__ == "__main__":
main()