首页 > 学院 > 开发设计 > 正文

人工智能—状态空间法(state space)[四]

2019-11-06 06:51:54
字体:
来源:转载
供稿:网友

这个题目是课上老师留下来的问题,然后借用之前传教士和狼的套路,将这个问题用编程实现。

题目描述:农夫需要把狼、羊、菜和自己运到河对岸去,只有农夫能够划船,而且船比较小,除农夫之外每次只能运一种东西,还有一个棘手问题,就是如果没有农夫看着,羊会偷吃菜,狼会吃羊。请考虑一种方法,让农夫能够安全地安排这些东西和他自己过河。

最终得出两套方案:

这里写图片描述

#以左岸为例a=1#农夫在左岸b=1#狼在左岸c=1#羊在左岸d=1#白菜在左岸class nongfu(): def __init__(self): pass def Operations(self,s): p1 =[s[0]-1,s[1]-1,s[2],s[3],0] p2 =[s[0]-1,s[1],s[2]-1,s[3],0] p3 =[s[0]-1,s[1],s[2],s[3]-1,0] p4 =[s[0]-1,s[1],s[2],s[3],0] p = [p1,p2,p3,p4] q1 =[s[0]+1,s[1]+1,s[2],s[3],1] q2 =[s[0]+1,s[1],s[2]+1,s[3],1] q3 =[s[0]+1,s[1],s[2],s[3]+1,1] q4 =[s[0]+1,s[1],s[2],s[3],1] q = [q1,q2,q3,q4] operators =[q,p] return operators def enable(self,operator): if operator[0]<0 or operator[1]<0 or operator[2]<0 or operator[3]<0: return False if a-operator[0]<0 or b-operator[1]<0 or c-operator[2]<0 or d-operator[3]<0: return False if ((b-operator[1])==1 and (c-operator[2])==1) and operator[0]==1: return False if ((c-operator[2])==1 and (d -operator[3])==1) and operator[0]==1: return False if operator[1] ==1 and operator[2] ==1 and operator[0]==0: return False if operator[2] ==1 and operator[3]==1 and operator[0]==0: return False return True def trun(self,states,operatorindex,roads,e): indexs =[] sign =0 a =0 tem = [] for s in states: for operator in self.operations(s)[e]: if self.enable(operator) : if operator not in roads: indexs.append(self.operations(s)[e].index(operator)) tem.append(operator) roads.append(operator) a =1 if a ==1: pass else: roads.append(['no way']) operatorindex =indexs states =tem e = abs(e-1) return states,operatorindex,roads,ee =1#初始状态左岸operatorindex =[' ']states =[[1,1,1,1,1]]roads = [[1,1,1,1,1]]nongfuPRo=nongfu()while roads[-1] !=[0,0,0,0,0]: [states,operatorindex,roads,e]=nongfupro.trun(states,operatorindex,roads,e)print roads
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表