在A *搜索中“跳跃”

时间:2014-03-06 16:48:56

标签: c++ algorithm a-star

我正在尝试实现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(&currentNode);
            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)

  
      
  1. 0 -2
  2.   
  3. -1 -2
  4.   
  5. -2 -2
  6.   
  7. -3 -2
  8.   
  9. -3 -1
  10.   
  11. -3 0
  12.   
  13. -4 0
  14.   
  15. -5 0
  16.   
  17. -5 1
  18.   
  19. -5 2
  20.   
  21. -5 3
  22.   
  23. -5 4
  24.   
  25. -6 4
  26.   
  27. -7 4
  28.   
  29. -5 5
  30.   
  31. -5 6
  32.   
  33. -3 1
  34.   
  35. -3 2
  36.   
  37. -3 3
  38.   
  39. -3 4
  40.   
  41. -2 4
  42.   
  43. -2 2
  44.   
  45. -4 6
  46.   
  47. -5 7
  48.   
  49. -8 4
  50.   
  51. -4 4
  52.   
  53. -5 -1
  54.   
  55. -1 -3
  56.   
  57. 1 -2
  58.   
  59. 2 -2
  60.   
  61. -1 -4
  62.   
  63. -2 -4
  64.   
  65. -3 -4
  66.   
  67. -5 -2
  68.   
  69. -9 4
  70.   
  71. -9 5
  72.   
  73. -9 6
  74.   
  75. -8 6
  76.   
  77. -7 6
  78.   

直到第14行似乎情况正常,但随后突然跳到(5,5)。 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

访问节点的顺序不一定是您的最短路径。据我所知,算法运行正常。观察到第12行中访问了节点-5 4,因此-5 5只是第15行中访问的该节点的邻居。要获得最短路径,您应该跟踪最终节点的parentNode返回算法末尾的初始节点。