A -star算法
提示:给出详细的A星算法介绍
原理
A-star算法在广度优先算法上做创新的。函数表达式为:
f(x)=g(x)+h(x),其中h(x)表示从当前状态位置点到达目标位置点最短路径;
源代码
def a_star_search(graph,start,goal):
#frontier存放这一回合探索的边界位置点
frontier=PriorityQueue()
frontier.put(start,0)
came_from={}#came_from是一个从当前位置到之前位置的映射。
cost_so_far={}#代表位置的当前代价
came_from[start]=None
#设置起点的当前代价为0
cost_so_far[start]=0
while not frontier.empty():#只要frontier队列中不为空,循环就不会停止
current=frontier.get()#抽取代价最低的位置点
if current==goal:#检查位置点是否是目标位置,如果是,则算法结束,否则,继续执行;
break
for next in graph.neighbors(current):#当前代价和预估代价
new_cost=cost_so_far[current]+graph.cost(current,next)#计算当前代价
if next not in cost_so_far or new_cost < cost_so_far[next]:
cost_so_far[next]=new_cost
#heuristic为预估代价
priority=new_cost+heuristic(goal,next)#当前代价加上预估代价;
frontier.put(next,priority)
came_from[next]=current
return came_from,cost_so_far
def heuristic(a,b):#此处采用的曼哈顿距离,实际情况可以采用欧式距离计算
(x1,y1)=a
(x2,y2)=b
return abs(x1-x2)+abs(y1-y2)