defis_goal(state): if state.lm == 0and state.lc == 0and state.rm == M and state.rc == C: return1 return0
能实施的操作用operators表示
1 2 3 4 5 6 7 8 9
# 合法操作 operators = []
# 根据k(船最大可容纳人数)生成合法操作,i为野人与传教士人数和,c为传教士数量 defget_operator(k): for i inrange(1,k + 1): for c inrange(i + 1): if (c >= i - c) or (c == 0): operators.append([c,i-c])
defis_dangerous(state): if state.lm >= 0and state.lc >= 0and state.rm >= 0and state.rc >= 0: if (state.lm >= state.lc and state.rm >= state.rc) or (state.lm == 0and state.rm >= state.rc) or (state.rm == 0and state.lm >= state.lc): return0 else: return1
defis_existed(state): for i in statelist: if (i.lm == state.lm and i.lc == state.lc and i.rm == state.rm and i.rc == state.rc and i.ship == state.ship): return1 return0 defdfs(start): global index,sum if is_goal(start):
sum += 1 print("第"+str(sum)+"种方案") for i in statelist: print(i.lm,i.lc,i.rm,i.rc,i.ship)
for i in operators: x = i[0] y = i[1]
if start.ship == 1: tmp = State(start.lm - x,start.rm + x, start.lc - y , start.rc + y, -1) if is_dangerous(tmp) == 0and is_existed(tmp) == 0: statelist.append(tmp) dfs(tmp) statelist.pop() else: tmp = State(start.lm + x, start.rm - x,start.lc + y , start.rc - y, 1) if is_dangerous(tmp) == 0and is_existed(tmp) == 0: statelist.append(tmp) dfs(tmp) statelist.pop()