I'm implementing the A* path find algorithm for a simple multi exit maze with varying distances, however I am unable to find an appropriate heuristic, it seems to perform a breadth-first search.
Cost is initial set to 1
Heres my attempt:
public void search(Node startNode, Node goalNode){
System.out.println("Search Started");
boolean found = false;
boolean noPath = false;
Queue<Node> open = new PriorityQueue<Node>(10,new Comparator<Node>(){
@Override
public int compare(Node t, Node t1) {
return Double.compare(t.getCost(), t1.getCost());
}
});
visited[startNode.getX()][startNode.getY()] = true;
order[startNode.getX()][startNode.getY()] = 0;
startNode.setCost(h(startNode, goalNode));
open.add(startNode);
while (found == false && noPath == false) {
if (open.isEmpty()) {
noPath = true;
}else{
Node current = open.remove();
if(current.getX() == goalNode.getX() && current.getY() == goalNode.getY()){
System.out.println("found Node");
printOrder();
found = true;
break;
}else{
for (int i = 0; i < 4; i++){
Node nextNode = getAction(current.getX(),current.getY());
System.out.println("getting node:" + nextNode.getX() + " " + nextNode.getY());
int g2 = current.getCost()+cost+h(current, goalNode);
System.err.println(g2);
nextNode.setCost(g2);
if (nextNode.getX() != -1) {
count++;
visited[nextNode.getX()][nextNode.getY()] = true;
order[nextNode.getX()][nextNode.getY()] = count;
open.add(nextNode);
}
}
}
}
}
}
Heuristic function
public int h(Node current, Node goal){
return (goal.getX() - current.getX()) + (goal.getY() - current.getY());
}
Help would be much appreciated
For the typical maze - one exit, only one path, path-width=1 - the A* has no advantage over breadth-first. Its difference is only visible for maps like you would see in strategy games where there is an advantage to trying to walk in the by-air-direction of the target and where the distance previously traveled has significance. If you like, have a look at the other algorithms: