[英]A* Pathfinding Algorithm — finding a path, but not optimal best path
我正在研究A *算法。 这是寻路方法的代码。 作为参考,以下是我正在使用的板: http : //i.imgur.com/xaAzNSw.png?1每个颜色图块都代表一个不同的启发式值。 由于某些未知的原因,它每次都会找到一条路径,但并不总是找到正确的路径。 这是寻路方法的代码。 如果有人需要任何澄清,我很乐意提供。
public List<Point> findPath(Point start, Point end) {
//declarations and instantiations
List<PathState> closedList = new ArrayList<PathState>(); //the nodes already considered
List<PathState> openList = new ArrayList<PathState>(); //nodes to be considered
openList.add(new PathState(start, end, tm)); //add starting point
PathState current = openList.get(0);
while(!current.isGoal()){
//sort open list to find the pathstate with the best hscore(sorts by hscore)
Collections.sort(openList);
current = openList.get(openList.size() - 1);
closedList.add(current);
openList.remove(current);
//get the valid children of current node
List<PathState> children = current.getChildren();;
if(!current.isGoal()){
for(int i = 0; i < children.size(); i++){
if(!closedList.contains(children.get(i))){
if(openList.contains(children.get(i))){
if(openList.get(openList.indexOf(children.get(i))).getgScore() > children.get(i).getgScore()){
//child is already on the open list, but this node has lower g value
//change g value and parent of node on open list
openList.get(openList.indexOf(children.get(i))).setG(children.get(i).getgScore());
openList.get(openList.indexOf(children.get(i))).changeParent(current);
}
}else{
//child not in closed list
openList.add(children.get(i));
//repaint the terrain panel with shades
tp.addAstarState(children.get(i));
tp.repaint();
try {
Thread.sleep(25);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
}
}
//returns the path from winning node to start for output
return current.getPath();
}
A *基本上是Djikstra的算法,但是您可以通过将距离函数与剩余距离的估计值结合起来将搜索定向到目的地。
在节点x上,djikstra的成本或“得分”为( distance_so_far )
在A *处为( distance_so_far + estimate_of_remaining_distance )
为确保A *找到最短路径, estimate_of_remaining_distance必须为真实的下限。 这意味着它必须始终小于实际剩余距离。 这意味着,您永远不能高估此距离,否则它将成为一种不精确的启发式方法,在这种情况下,它不一定会找到最短的路径。
这是一个很好的参考: http : //theory.stanford.edu/~amitp/GameProgramming/AStarComparison.html
它链接到此参考资料,该参考资料进一步解释了启发式功能: http : //theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.