【发布时间】:2015-09-22 18:23:12
【问题描述】:
我正在尝试在 C++ 中实现迭代加深深度优先搜索算法。搜索成功找到了问题的解决方案,但我无法将子节点链接回根节点。
struct Node
{
std::vector<int> config;
int depth;
int action; //0 up 1 down 2 left 3 right
Node * parent;
bool operator<(const Node& rhs) const
{
return depth < rhs.depth;
}
};
正如您在我的结构中看到的,我有一个指向父节点的指针。然而,在我的 DFS 代码中,我遇到了在循环的每次迭代中更新节点的父指针的问题。所有节点的父指针总是指向同一个数据位置,0xfffffffd2b0。换句话说,名为 Next 的新节点总是在这里创建。
我相信我在代码中名为 Next 的节点总是被放置在同一个数据位置,因此每个 Next 的引用位置总是相同的。如何防止它总是出现在同一个位置?这意味着子节点没有链接到它们的父节点,而是链接到它们自己。我已经用星号标记了错误的来源。
//IDDFS Logic:
int Current_Max_Depth = 0;
while(Current_Max_Depth < 20)
{
struct Node initial = {orig_config, 0, 0, NULL}; //config, depth, action, parent.
visited.clear();
priority_queue<Node> frontier;
frontier.push(initial);
while(frontier.size()>0)
{
struct Node Next = frontier.top();
visited.push_back(Next.config);
frontier.pop();
if(Next.depth < Current_Max_Depth)
{
int pos_of_hole = Find_Position_of_Hole(Next.config);
if(pos_of_hole==0)
{
std::vector<int> Down_Child = Move_Down(Next.config);
struct Node Down_Node = {Down_Child,Next.depth+1,1,&Next}; //****
if(!(std::find(visited.begin(), visited.end(), Down_Child)!=visited.end()))
{
if(Goal_Test(Down_Child))
{
goal_node = Down_Node;
goal_reached = true;
break;
}
frontier.push(Down_Node);
}
std::vector<int> Right_Child = Move_Right(Next.config);
struct Node Right_Node = {Right_Child,Next.depth+1,3,&Next}; //*******Passing next by reference here is not working since Next is always at the same data location. The nodes one layer up from the leaf nodes end up all pointing to themselves.
if(!(std::find(visited.begin(), visited.end(), Right_Child)!=visited.end()))
{
if(Goal_Test(Right_Child))
{
goal_node = Right_Node;
goal_reached = true;
break;
}
frontier.push(Right_Node);
}
}
if(pos_of_hole==1)
... does very similar for pos 1 through 8, not related to bug ...
} //End of if(Next.Depth < Max_Depth)
} //End of while(frontier.size()>0)
if(goal_reached)
{
break;
}
Current_Max_Depth++;
}
【问题讨论】:
-
0xfffffffd2b0通常表示堆栈位置
标签: c++ pointers memory-management