java - [JAVA] A-Star 代码未找到最佳路径

标签 java algorithm

我正在尝试编写 A* 搜索算法的代码,但我似乎无法让它工作。我正在从维基百科复制伪代码。我的代码似乎只是搜索每个可能的节点。这是我的 showPath() 函数:

public void showPath() {
Nodes current = end;

while(current.cameFrom!=null) {
    current.isPath = true;
    current = current.cameFrom;
}
}

起始节点将有一个 null 的 cameFrom,因为这是它的默认值。

public void A_Star() {
PriorityQueue<Nodes> closedSet = new PriorityQueue<Nodes>();
PriorityQueue<Nodes> openSet = new PriorityQueue<Nodes>();
closedSet.clear();
openSet.clear();

start.gScore = 0;
openSet.add(start);
start.fScore = getDist(start,end);

while(!(openSet.size() ==0)) {
    Nodes curr = openSet.poll();
    if(curr.x == end.x && curr.y == end.y) {
        showPath();
    }
    closedSet.add(curr);
    for(int i=0;i<curr.getNeighbourCount();i++) {
        Nodes neighbour = curr.getNeighbour(i);
        if(closedSet.contains(neighbour)) {
            continue;
        }
        //isPassable is a boolean that is false if the Nodes is an obstacle
        if(!openSet.contains(neighbour) && neighbour.isPassable) {
            openSet.add(neighbour);
        }
        //It's a grid so every point is a distance of 1 from it's neighbours
        else if((curr.gScore+1)>= neighbour.gScore){
            continue;
        }
        neighbour.cameFrom = curr;
        neighbour.gScore = curr.gScore+1;
        neighbour.fScore = neighbour.gScore + getDist(neighbour,end);

    }

}

编辑:我的 getDist 函数

public int getDist(Nodes node1, Nodes node2) {
    return ( Math.abs(node1.x - node2.x) + Math.abs(node1.y - node2.y));
}

最佳答案

如果你看这个picure ,你必须注意到,对于曼哈顿距离,从起点到终点的所有路径都具有相等的距离。这将导致您将访问所有内容。

将您的距离更改为欧氏距离。

关于java - [JAVA] A-Star 代码未找到最佳路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52803506/

相关文章:

java - 如何删除默认边框以及如何锚定 jtable 的列标题?

algorithm - 检测重复的行组

java - 最长的盈利交易算法

python - 如何构建这个 OpenCL 暴力破解代码

c# - 如何在 .net 中加密文件并在 android 中解密

java - 检查异常对此方法无效

java - SHA-1 哈希在使用自定义 REALM 的基于 jboss 表单的身份验证中不起作用

java - 为什么在工厂方法和方法引用(单例/原型(prototype))中使用 lambda 时功能接口(interface)初始化不同?

java - Java 中的 ServicePointManager 等价物

python - 通过最小化迭代次数来改进代码