我已经编写了代码,试图解决传教士和食人族的问题,并已实施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);
}
请**您的问题与[mcve]或[SSCCE(Short,Self Contained,Correct Example)](http://sscce.org) – NathanOliver
您的默认'Node'构造函数不会初始化'父母'(可能与你遇到的问题无关)。 – crashmstr
另外,'applyMoves'按值取'current_node',然后使用它的地址。 – crashmstr