gpt4 book ai didi

c++ - 无法创建由 "Parent"链接的元素列表

转载 作者:太空宇宙 更新时间:2023-11-04 14:27:50 25 4
gpt4 key购买 nike

我正在尝试创建一种方法(使用 *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 崩溃。

//目标是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 而它应该指向列表中的节点 opened

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

最佳答案

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

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

执行后n将是初始节点

关于c++ - 无法创建由 "Parent"链接的元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2374641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com