首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >[JAVA} A-Star代码找不到最佳路径

[JAVA} A-Star代码找不到最佳路径
EN

Stack Overflow用户
提问于 2018-10-14 22:09:50
回答 1查看 67关注 0票数 1

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

public void showPath() {
Nodes current = end;

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

start节点的cameFrom将为null,因为这是它的默认值。

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));
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-15 05:49:54

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

将距离更改为欧式距离。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52803506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档