实现A星搜索C ++的问题

时间:2017-11-29 17:14:34

标签: c++ algorithm a-star

我正在尝试在我正在创建的游戏中使用C ++实现一个A star算法并且它无法正常工作,我真的不知道是否有关于代码或算法的错过。我已经使用了集合,因为它们已经排序,返回值是一个带有我必须访问的节点的向量。我之前从未使用过这个算法,所以我可能会遇到某种错误。

struct node {
    Pos pos;
    int f; //the sum of the distance from the goal to succcessor
    int g; // the sum of the cost of the current plus the one from the successor
    int h; //distance from goal to successor

friend bool operator< (node right, node left)  {
      return (right.f < left.f);
    } };



vector<node> search(Pos inicio,Pos desti){

    set<node> opennodes;
    vector<node> closednodes;
    node inici;
    node successor;
    inici.pos = inicio;
    inici.h = heuristic(inicio,desti);
    inici.g = getcost(inicio); 
    inici.f = inici.g + inici.h;
    opennodes.insert(inici);
    closednodes.push_back(inici);
    while(not opennodes.empty()){
        node current = *(opennodes.begin());
        opennodes.erase(opennodes.begin());
        if(current.pos == desti) cerr<<"encontrao";
        Dir direccio;
        for(int i = 0; i < 4;++i){
            if(i==0){
                    direccio = LEFT;

            }
            else if(i==1){
                    direccio = RIGHT;
            }
            else if(i==2){
                    direccio = TOP;
            }
            else {
                    direccio = BOTTOM;
            }

                successor.pos = current.pos + direccio;
                if(successor.pos == desti) return closednodes;
                if(pos_ok(successor.pos)){
                    successor.g = current.g + getcost(successor.pos);
                    successor.h = heuristic(successor.pos,desti);
                    successor.f = successor.g + successor.h;

                    node n1 = checkposition(successor.pos, opennodes); //I had to create two checkposition just to know if there's the node in the set or in the vector
                    node n2 = checkposition2(successor.pos, closednodes); 

                    if (n1.f != -1 and n1.f < successor.f);
                    else if (n2.f != -1 and n2.f < successor.f);
                    else opennodes.insert(successor);

                }
        }
          closednodes.push_back(current); 
        }

    return closednodes;
}

1 个答案:

答案 0 :(得分:0)

所以,首先:

If (DenseRank (Sum ([totalsales]) OVER ([name_client]), "desc") <= 10, [name_client], "Others")

这里不应该有中断声明吗? cerr函数不会破坏你的循环,只会抛出错误消息到你的标准输出。

你内部的for语句总是运行到4,所以direccio总是设置为BOTTOM。 除此之外,我认为启发式很好,问题出在代码结构中,我建议调试它并在此处发布你的结果。