【A-star算法的学习】

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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值