跳转至

创建路径列表

最后,是时候实现 makeList() 函数了:

template<int WIDTH, int HEIGHT>
void makeList(
    AStarNodePtr end,
    std::vector<AStarNodePtr> nodes,
    int path[WIDTH][HEIGHT])
{
    for (auto n = nodes.begin(); n != nodes.end(); 
n++)
      path[(*n)->x][(*n)->y] = 2;
    auto node = end;
    while (node.get() != nullptr) {
      path[node->x][node->y] = 1;
      node = node->parent;
    }
}

这个函数用关闭节点列表①和计算出的路径②更新 path。本例中,值 2 表示关闭节点,1 表示路径节点。程序通过从目标节点沿着父节点一直走到起始节点(父节点为 nullptr 的孤儿)来计算路径中的节点。