无法创建由“父”链接的元素列表

时间:2010-03-03 20:21:17

标签: c++ pointers list iterator a-star

我正在尝试创建一个方法(使用* A **算法)来解决难题并将步骤返回到该解决方案。解决方案很容易..但我无法回到原点。

我使用了一个节点列表,然后每次推回一个新节点我设置指向新节点的节点的父节点;

list<Node> opened;
list<Node> closed;

Node current;

opened.push_back(start);

while( opened.size() !=0 )
{
   current = getLowestCostPath(opened);


   if(IsSolution(current) == true)
       return opened;

   opened.remove(current);

   if( !Has(closed, current))
          closed.push_back(current);


   for( int i = 0; i < static_cast<int>(current.GetBoard().capacity()); i++ ) 
   {   
   xx = current.GetBoard()[i].X();
   yy = current.GetBoard()[i].Y();

       for(int j = 0; j < static_cast<int>(current.GetBoard().capacity()); j++) 
       {
            if( isMovable(current))
            {
                //if found a new node
                Node newNode = Node(newBoard);
                Node *t = &current;

                if(!Has(opened, newNode ) && !Has(closed, newNode ) )
                {
                   newNode.SetParent(t);
                   opened.push_back(newPath);
                }
            }
        }
    }
}

(..)

类Node它只是这个

class Node{

public:
   std::vector<Point> board;
   Path *parent;

   Node();
   Node(std::vector<Point> board)

   virtual std::vector<Point> GetBoard() const;
   virtual Path* GetParent() const;
   virtual void SetParent(Node *p); 

Node::Node(): board(),parent(NULL)
{
}

std::vector<Point> Node::GetBoard() const
{
return board;
}

void Path::SetParent(Node *p)
{
    this->parent = p;
}

Path* Path::GetParent() const
{
    return parent;
}

但后来我意识到我无法建立解决难题的道路......

我甚至看不到一个单亲董事会......

for( list<Node>::iterator it = goal.begin(); it != goal.end(); it++)
{
    if( (*it).GetParent() != NULL ){
        cout << "writing a board" << endl;
        mas::WriteLine( (*it).GetParent()->GetBoard() , "\n");
    }
}

我在互联网上搜索过,我无法意识到我做错了什么:(


我也试过了,但它让VS2005崩溃了。

// goal它是Solve方法返回的打开列表....

for(std::list<Node>::iterator it = goal.end(); it->GetParent() != NULL; t->GetParent())
{

    std::cout << "step" << std::endl;
    mas::WriteLine((*it).GetBoard(), "\n");
}

我正在努力变得更加清晰和客观。所以...看这个部分

current = getLowestCostPath(opened);

getLowestCostPath方法返回的值来自:

Node Solution::getLowestCostPath( std::list<Node> l)
{
    std::list<Node>::reverse_iterator min = l.rbegin();
    int value = 0;
    for(std::list<Node>::reverse_iterator it = l.rbegin(); it != l.rend(); it++)
    {
        if( value < (*it).GetStep())
        {   
            min = it;
            value = (*it).GetStep();
        }
    }
    return *min;
}

之后...在方法Solve上..这部分代码

//if found a new node
Node newNode = Node(newBoard);
Node *t = &current;

newPath.SetParent(t);

我认为这部分的错误是 newPath 它指向 t 时它应该指向列表上的节点打开

这是真的吗?如果是..我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

你的代码量需要更深入的调查,但基本上我看到你错误地追溯你的方式。假设n是你的最终节点。然后像这样回来

for (; n->GetParent() != NULL; n = n->GetParent())
  //do something on each node

执行此操作后,n将成为初始节点