1.初始化问题
用三元组来表示状态[M,C,B],M:传教士人数,C:野人数,B:船的位置(1表示在左岸,0表示在右岸),假设初始都在左岸。
if __name__ == '__main__':
N = int(input("传教士和野人的人数(默认相同):"))
K = int(input("船的最大容量:"))
open = [] # 创建open表
closed = [] # 创建closed表
sample = [N, N, 1] # 初始状态
goal = [0, 0, 0] # 目标状态
open.append([sample]) # 初始状态放入open表
creatpoint = searchpoint = 0 # 生成节点数和搜索节点数
2.启发函数
用h(n)=M+C-K*B来作为启发函数,每次左岸的总人数尽可能少。
def heuristic(this, k): # 启发函数计算 h(n) = M + C - K * B
return this[0] + this[1] - k * this[2]
3.获取后继节点
分为左右两岸两种情况,每种情况又分只过传教士、只过野人、过传教士和野人三种情况,最后用启发函数重新排open表。
# 扩展节点
searchpoint += 1
if this[0][2] == 1: # 船在左岸时
for i in range(1, K + 1): # 只过传教士
if creat(this, this[0][0] - i, this[0][1], this[0][2], N):
creatpoint += 1
for i in range(1, K + 1): # 只过野人
if creat(this, this[0][0], this[0][1] - i, this[0][2], N):
creatpoint += 1
for i in range(1, K): # 过传教士和野人
for r in range(1, K - i + 1):
if creat(this, this[0][0] - i, this[0][1] - r, this[0][2], N):
creatpoint += 1
else: # 船在右岸时
for i in range(1, K + 1): # 只过传教士
if creat(this, this[0][0] + i, this[0][1], this[0][2], N):
creatpoint += 1
for i in range(1,