我正在尝试编写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));
}
发布于 2018-10-15 05:49:54
如果你看这个picure,你必须注意到,对于Manhatten距离,从起点到目标的所有路径都具有相等的距离。这将导致,您将访问所有。
将距离更改为欧式距离。
https://stackoverflow.com/questions/52803506
复制相似问题