1
我試圖實現A *搜索算法,這裏是我的嘗試:「跳躍」,在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行,但t它突然跳到(5,5)。 任何幫助,非常感謝。
我們是否應該假設您輸出的結果與您的代碼中的'cout << i ++ <<「。<< << currentNode.getX()<<」<< << currentNode.getY()'相同? –
是的,這是正確的。 – SpiderRico
然後,我們不是在觀看節點從OpenList獲取的順序嗎?如果是這樣的話,這實際上並不是一條路徑,它只是節點正在被檢查的順序,在這種情況下,這可能是確定的,這取決於啓發式,如果地圖完全是空的(沒有障礙或改變沿網格的啓發式等)。 –