Недавно я реализовал алгоритм A * для моей модели на основе агента, которая использует 2D-массив. Целью поиска является предоставление агентам списка мест, которые ведут к местоположению цели. Моя реализация работает, однако несколько раз, когда я выполняю алгоритм, он возвращает альтернативный путь, который все еще связан с основным путем. Я не понимаю, почему он это делает. Введите код ниже: http://pbrd.co/1DFaeIr
public boolean generatePath(Location startLocation, Location goalLocation) {
setUpStartingPoint(startLocation, goalLocation); //Set up everything before search
boolean pathExist = false;
int loop = 0;
openList.add(startNode); //Put start node in openList (Initial starting point)
while(pathExist == false) {
if(openList.isEmpty() == false) { //More locations to check
System.out.println("Step: " + loop);
System.out.println(currentNode);
System.out.println(openList);
System.out.println(closedList);
reOrderList(openList);
Node lowestFvalueNode = openList.remove(0); //Get the node with the lowest F value in openList
lowestFvalueNode.setParent(currentNode);
currentNode = lowestFvalueNode;
closedList.add(lowestFvalueNode);
if(checkNodeInList(closedList, goalNode)) {
System.out.println("Found");
computeCurrentPath(currentNode);
pathExist = true;
}
else {
ArrayList<Node> currentNodeAdjNodes = getAdjacentNodes(currentNode);
for(Node adjNode : currentNodeAdjNodes) {
if(checkNodeInList(closedList, adjNode)) { //If node is in the closedList
}
else {
if(checkNodeInList(openList, adjNode) == false) {
computeNodeValues(adjNode); //Compute the G,H and F values of node
adjNode.setParent(currentNode); //Set the nodes parent as current node
openList.add(adjNode); //Add node to open list
}
else {
Node actualAdjNodeInOpenList = getNodeInList(openList, adjNode);
int currentMovementCostToNode = currentNode.getGvalue() + getMovementCostToNode(currentNode, adjNode);
if(currentMovementCostToNode < adjNode.getGvalue()) {
computeNodeValues(adjNode);
adjNode.setParent(currentNode);
reOrderList(openList);
}
}
}
}
}
loop++;
}
else {
pathExist = false;
System.out.println("Path doesn't exist");
return false;
}
}
System.out.println(path);
return pathExist;
}
Если путь оптимален, тогда не имеет значения, какой из них вы выберете. Существует способ оптимизации алгоритма, который стоит попробовать: используйте A * вместе с Beam search. Поиск луча уменьшит необходимое пространство памяти.