-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.cpp
More file actions
60 lines (53 loc) · 1.59 KB
/
Copy pathnode.cpp
File metadata and controls
60 lines (53 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "fifteenPuzzle.h"
using namespace std;
Node::Node(const uint8_t state[16], Node* parent, int action){
memcpy(this->state, state, 16 * sizeof(uint8_t));
this->parent = parent;
this->action = action;
this->depth = parent ? parent->depth + 1 : 0;
}
void Node::expand(const Problem* problem, std::vector<unique_ptr<Node>>& result){
auto actions = problem->actions(this->state);
switch (this->action){
case 0:
actions[2] = false;
break;
case 1:
actions[3] = false;
break;
case 2:
actions[0] = false;
break;
case 3:
actions[1] = false;
break;
}
for(int i=0; i<4; i++){
if(actions[i]){
result.push_back(unique_ptr<Node>(child_node(problem, i)));
}
}
}
Node* Node::child_node(const Problem* problem, int action){
auto next_state = problem->result(this->state, action);
auto next_node = new Node(next_state.get(), this, action);
return next_node;
}
unique_ptr<vector<int>> Node::solution(){
auto path = this->path();
unique_ptr<vector<int>> solution(new vector<int>());
for(int i=0; i<path.get()->size(); i++){
(solution.get())->push_back((*path)[i]->action);
}
return solution;
}
unique_ptr<vector<Node*>> Node::path(){
auto node = this;
unique_ptr<vector<Node*>> path_back(new vector<Node*>());
while(node){
(path_back.get())->push_back(node);
node = node->parent;
}
reverse(path_back.get()->begin(), path_back.get()->end());
return path_back;
}