【发布时间】:2015-10-14 15:31:12
【问题描述】:
我编写了试图解决传教士和食人者问题的代码,并实现了Node 以将信息保存在Node::arr 和Node::parent 中。这些,当由函数bfs 返回时,将给出最短路径中的状态。
当bfs 返回时,它有正确的parents 编号。然而,当我在 Visual Studio 调试器中检查Node last 时,我注意到它的parents.arr 包含垃圾,即arr[0]=-858993460。但是Node last 有正确的arr(问题的最终状态{0,0,1,3,3,0})。这些信息是如何丢失的?
node.h
#pragma once
#include <array>
class Node {
public:
std::array<int, 6> arr;
Node *parent;
Node(std::array<int, 6> arr, Node *parent = NULL);
Node();
};
node.cpp
#include "Node.h"
Node::Node(std::array<int, 6> arr, Node *parent) : arr(arr), parent(parent) {};
Node::Node(): parent(NULL) {};
main.cpp
void applyMoves(queue<Node> &q, Node current_node, array<int, 3> moves) {
array<int, 6> arr = current_node.arr;
array<int, 3> left, right;
// apply valid moves to arr
// copy the arr to left and right and check if the move applied are valid
// if valid and no duplicates in the queue do proceed to the next lines below
Node n = Node(arr, ¤t_node);
q.push(n);
}
Node bfs(queue<Node> &q, array<array<int, 3>, 5> moves) {
while (!q.empty()) {
Node current = q.front();
q.pop();
if (achievedGoal(current.arr) == 1) {
return current;
}
for (const auto& move : moves) {
applyMoves(q, current, move);
}
}
Node n;
return n;
}
int main() {
array<int, 6> init_state{ 3,3,1,0,0,0 };
array<array<int, 3>, 5> moves{ { {1,0,1}, {0,1,1}, {1,1,1}, {2,0,1}, {0,2,1} } };
Node n = Node(init_state);
queue<Node> q;
q.push(n);
Node last = bfs(q, moves);
}
【问题讨论】:
-
您的默认
Node构造函数未初始化parent(可能与您遇到的问题无关)。 -
另外,
applyMoves采用current_node的值,然后你使用它的地址。 -
@crashmstr 我将
applyMoves更改为接收Node &current_node并像这样调用applyMoves(q, current, move);但是,当我检查Node last时,似乎有一个永无止境的“级别”parent指向parent