-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFPKState.hpp
114 lines (95 loc) · 3.43 KB
/
FPKState.hpp
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
103
104
105
106
107
108
109
110
111
112
113
114
#pragma once
#include <vector>
#include <queue>
#include "StateBase.hpp"
using namespace std;
class FPKState : public StateBase{
public:
FPKState* parent;
FPKState(vector<vector<int>> currState, int g, FPKState* parent, vector<int>* knightDistances) : currState(currState), parent(parent), knightDistances(knightDistances){
this->g = g;
this->updateHeuristicSum();
};
template <typename C, typename T>
void generateSuccessor(priority_queue<T*, vector<T*>, C>& pq) {
int zeroi;
int zeroj;
for (size_t i = 0; i < this->currState.size(); i++){
for (size_t j = 0; j < this->currState[0].size(); j++){
if (!this->currState[i][j]){
zeroi = i;
zeroj = j;
}
}
}
for (size_t i = 0; i < this->currState.size(); i++){
for (size_t j = 0; j < this->currState[0].size(); j++){
if (canJumpTo(zeroi, zeroj, i, j)){
swap(this->currState[zeroi][zeroj], this->currState[i][j]);
FPKState* child = new FPKState(this->currState, this->g + 1, this, this->knightDistances);
pq.push(child);
swap(this->currState[zeroi][zeroj], this->currState[i][j]);
}
}
}
}
bool reachGoalState() override {
for (size_t i = 0; i < this->currState.size(); i++){
for (size_t j = 0; j < this->currState[0].size(); j++){
if (currState[i][j] != 0 && (4 * i + j) != (currState[i][j] - 1)){
return false;
}
}
}
return true;
}
void Recurse_Print(ofstream& output) {
if (this->parent){
this->parent->Recurse_Print(output);
}
for (auto& i : this->currState){
for (auto j : i){
output << j << " ";
}
output << endl;
}
output << endl;
}
void Print_Res(string& inputFilePath) override {
StateBase::Print_Res(inputFilePath);
ofstream output;
output.open(inputFilePath);
output << "length = " << this->g << endl;
output << endl;
this->Recurse_Print(output);
output.close();
}
protected:
void updateHeuristicSum() override {
int h = calcH();
this->f = this->g + h;
}
private:
vector<vector<int>> currState;
vector<int>* knightDistances;
int calcH(){
int distSum = 0;
for (size_t i = 0; i < this->currState.size(); i++){
for (size_t j = 0; j < this->currState[0].size(); j++){
int currLoc = 4 * i + j;
int currNum = this->currState[i][j] - 1;
if (currNum == -1){
continue;
}
distSum += (*(this->knightDistances))[16 * currLoc + currNum];
}
}
return distSum;
}
};
class FPKComp{
public:
bool operator() (const FPKState* a, const FPKState* b) const{
return a->f > b->f;
}
};