A *寻路算法 - 寻找路径,但不是最佳路径

时间:2014-12-10 03:12:59

标签: java path-finding a-star

我正在研究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();
}

1 个答案:

答案 0 :(得分:3)

A *基本上是Djikstra的算法,但是你可以通过将距离函数与剩余距离的估计结合起来将搜索引导到目的地。

在节点x,费用或&#34;得分&#34;是( distance_so_far )djikstra

<*>在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