我正在尝试实现A *搜索算法,这是我的尝试:
void Map::findPath(Robot robot, Model target, vector<Node> nodeList, vector<Node> &closedList) {
Node targetNode = target.getCurrentNode();
Node startNode = robot.getCurrentNode();
vector<Node> openList;
openList.push_back(startNode);
startNode.setG(0);startNode.setH(0);startNode.setF(0);
int i = 0;
while (!openList.empty()) {
Node currentNode = nodeWithLowestFScore(openList);//always returns the most recent one
/*for ( int i = 0; i < openList.size(); i++){
cout << "X: " << openList[i].getX() << " Y: " << openList[i].getY() <<
" G: " << openList[i].getG() << " M: " << openList[i].getH() << endl;
}*/
cout << i++ << ". " << currentNode.getX() << " " << currentNode.getY() << " G: " <<
currentNode.getG() << " M: " << currentNode.getH() << endl;
closedList.push_back(currentNode);
removeFromVector(openList, currentNode);
if (inVector(closedList, targetNode))
break;
vector<Node> adjacentNodes;
currentNode.getWalkableAdjacentNodes(nodeList, adjacentNodes);
for ( int i = 0; i < adjacentNodes.size(); i++){
if (inVector(closedList, adjacentNodes[i]))
continue;
if (!inVector(openList, adjacentNodes[i])){
adjacentNodes[i].setParent(¤tNode);
adjacentNodes[i].setG(currentNode.getG() +1);//distance is always 1 between adjacent nodes
adjacentNodes[i].setH(adjacentNodes[i].getDistance(targetNode, 'm'));//heuristic as manhattan
adjacentNodes[i].setF(adjacentNodes[i].getG() + adjacentNodes[i].getH());
openList.push_back(adjacentNodes[i]);
}
if (inVector(openList, adjacentNodes[i])){//update if it's in the list already
//?
}
}
}
}
我认为函数的名称是自解释的,所以我不会进入它们。无论如何,在我的示例输出中,我试图从(x:0,y:-2)到(x:-7,y:6)
- 0 -2
- -1 -2
- -2 -2
- -3 -2
- -3 -1
- -3 0
- -4 0
- -5 0
- -5 1
- -5 2
- -5 3
- -5 4
- -6 4
- -7 4
- -5 5
- -5 6
- -3 1
- -3 2
- -3 3
- -3 4
- -2 4
- -2 2
- -4 6
- -5 7
- -8 4
- -4 4
- -5 -1
- -1 -3
- 1 -2
- 2 -2
- -1 -4
- -2 -4
- -3 -4
- -5 -2
- -9 4
- -9 5
- -9 6
- -8 6
- -7 6
醇>
直到第14行似乎情况正常,但随后突然跳到(5,5)。 非常感谢任何帮助。
答案 0 :(得分:1)
访问节点的顺序不一定是您的最短路径。据我所知,算法运行正常。观察到第12行中访问了节点-5 4
,因此-5 5
只是第15行中访问的该节点的邻居。要获得最短路径,您应该跟踪最终节点的parentNode返回算法末尾的初始节点。