A*搜索算法AStar_BFS
算法原理: 利用优先队列(优先级属性每一个结点的估计函数值+当前的路径消耗值)后进先出的性质来一层层的遍历。最佳优先搜索的最广为人知的形式称为 A* 搜索。它对结点的评估结合了到达此结点已经花费的代价,和从该结点到目标结点所花代价。由于结合了从开始结点到结点 n 的路径代价和从结点 n 到目标结点的最小代价路径的评估值,因此评估函数值等于经过结点 n 的最小代价解的估计代价。
算法时间空间复杂度分析:时间复杂度:O(b^m ),空间复杂度:O(b^m )
算法步骤:
1)将开始结点压入优先队列中;
2)取出队列结点当前拓展结点,设置为已访问;
3)判断当前结点是否为目标结点,若是则输出路径搜索结束,否则进行下一步;
4)访问当前结点的所有相邻子节点;
5)判断该该子节点是否被访问过,若已经访问过则回到2),若还未访问过则继续下一步6);
6)对于每一个子节点,获取其相关信息值并进行路径更新,将其子节点的父亲结点指向当前结点,返回2);
7)对新的队列进行一次优先级排序;
8)若优先队列为空还未找到目标结点,返回搜索失败;
package 实验一;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class AStar_BFS extends BuildGraph{
public void ShortestPath(){
ShortestPath(start,end);
}
public Queue<Vertex> SortTest(Queue<Vertex> queue){
List<Vertex> list=new ArrayList<>();
while(!queue.isEmpty()){
list.add(queue.poll());
}
Collections.sort(list, new Comparator<Vertex>(){
@Override
public int compare(Vertex o1, Vertex o2) {
// TODO Auto-generated method stub
return (o1.dist+o1.h)<(o2.dist+o2.h)? -1:((o1.dist+o1.h)==(o2.dist+o2.h)? 0:1);
}
});
int i=0;
while(i<list.size()){
//System.out.println(list.get(i).h);
queue.add(list.get(i));
i++;
}
return queue;
}
public void ShortestPath(Vertex startNode,Vertex endNode){
//初始化
Queue<Vertex> queue = new LinkedList<>();
//startNode.dist=0;
queue.offer(startNode);//将源点dist设置为0并入队列
while(!queue.isEmpty()){
Vertex v = queue.poll();
explored.put(v.vertexLabel, 1);
if(v.vertexLabel==endNode.vertexLabel){
System.out.println("AStar_BFS Route:");
showPath_A(v,startNode);
return;
}
for(int i=0;i<v.child.size();i++){
Vertex current=v.child.get(i).endVertex;
//System.out.println(explored.get(current.vertexLabel));
if(explored.get(current.vertexLabel)==0){
current.dist=v.dist+v.adjEdges.get(v.child.get(i));
queue.offer(current);
current.preNode=v;
}
}
queue=SortTest(queue);
}
System.out.println("AStar_BFS Route:"+" Failure!");
return;
}
}