Repository navigation
Expand file tree
/
Copy pathNode.cpp
More file actions
102 lines (87 loc) · 3.02 KB
/
Copy pathNode.cpp
File metadata and controls
102 lines (87 loc) · 3.02 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "Node.hpp"
Node::Node(std::string state, int cost, std::list<std::string> path, int index){
this->state = state;
this->cost = cost;
this->path = path;
// Update the index of the pieces
this->index = index;
};
Node::~Node() = default;
std::string Node::changeState(int originPiece, int destinyPiece){
std::string newState;
// Find first piece
newState = this->state;
char firstPiece = newState[originPiece*2];
newState[originPiece*2] = newState[destinyPiece*2];
newState[destinyPiece*2] = firstPiece;
return newState;
}
std::vector<Node> Node::expandNode(int columns, int rows){
std::vector<Node> expandedNodes;
// Check the possible moves
int indexBlankPiece = this->index;
// for (int i=0; i<rows*columns; i++){
// std::cout<< "Index of piece "<< i+1<< ": "<< this->indices[i]<< endLine;
// }
// std::cout<< indexBlankPiece<< endLine;
// std::cout<< this->state[indexBlankPiece*2]<< endLine;
// New state
std::string newState;
// Move leftside
if (indexBlankPiece % columns != 0){
newState = changeState(indexBlankPiece, indexBlankPiece-1);
Node node = Node(newState, this->cost, this->path, indexBlankPiece-1);
node.path.push_back(node.state);
expandedNodes.push_back(node);
}
// Move downside
if (indexBlankPiece < (rows-1)*columns){
newState = changeState(indexBlankPiece, indexBlankPiece+columns);
Node node = Node(newState, this->cost, this->path, indexBlankPiece+columns);
node.path.push_back(node.state);
expandedNodes.push_back(node);
}
// Move rightside
if (indexBlankPiece % columns != columns-1){
newState = changeState(indexBlankPiece, indexBlankPiece+1);
Node node = Node(newState, this->cost, this->path, indexBlankPiece+1);
node.path.push_back(node.state);
expandedNodes.push_back(node);
}
// Move upside
if (indexBlankPiece >= columns){
newState = changeState(indexBlankPiece, indexBlankPiece-columns);
Node node = Node(newState, this->cost, this->path, indexBlankPiece-columns);
node.path.push_back(node.state);
expandedNodes.push_back(node);
}
return expandedNodes;
}
void Node::printState(int columns, int rows){
int position = 0;
for (int i=0; i<rows; i++){
// First row
if (i == 0){
std::cout<< "\t-------------"<< endLine;
}
for (int j=0; j<columns; j++){
// First column
if (j == 0){
std::cout<< "\t| "<<this->state[position]<< " ";
}
else{
if (j < columns-1){
std::cout<< "| "<<this->state[position]<< " |";
}
// Last column
else{
std::cout<< " "<< state[position]<< " |";
}
}
position += 2;
}
std::cout<< endLine;
}
// Close the puzzle
std::cout<< "\t-------------"<< endLine;
}