我已經編寫了代碼,試圖解決傳教士和食人族的問題,並已實施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