-
Notifications
You must be signed in to change notification settings - Fork 0
/
State.cpp
143 lines (126 loc) · 2.35 KB
/
State.cpp
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include "State.h"
#include <unordered_map>
#include <iostream>
using namespace std;
State::State(int a[ROW][COL])
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
num[i][j] = a[i][j];
if (a[i][j] == 0)
{
zeroRow = i;
zeroCol = j;
}
}
}
this->f = 0;
this->g = 0;
this->h = 0;
this->parent = nullptr;
}
State::~State()
{
}
State::State(const State & state)
{
zeroRow = state.zeroRow;
zeroCol = state.zeroCol;
f = state.f;
g = state.g;
h = state.h;
parent = state.parent;
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
num[i][j] = state.num[i][j];
}
void State::setH(const State & goal)
{
unordered_map<int, pair<int, int>> theMap; //key为元素值,value为该数码的位置
unordered_map<int, pair<int, int>> goalMap;
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
{
theMap[this->num[i][j]] = pair<int, int>(i, j);
goalMap[goal.num[i][j]] = pair<int, int>(i, j);
}
for (int i = 1; i < 9; i++)
{
int dx = abs(theMap[i].first - goalMap[i].first);
int dy = abs(theMap[i].second - goalMap[i].second);
h += (dx + dy);
}
}
void State::setG(int depth)
{
this->g = depth;
}
void State::setF()
{
f = g + h;
}
bool State::operator==(const State & state) const
{
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
{
if (num[i][j] != state.num[i][j])
return false;
}
return true;
}
std::vector<State> State::getSuccessor()
{
std::vector<State> ret;
int direction[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
for (int i = 0; i < 4; i++)
{
int xi = this->zeroRow + direction[i][0];
int yi = this->zeroCol + direction[i][1];
if (xi >= 0 && xi < ROW && yi >= 0 && yi < COL)
{
int b[COL][ROW];
//将当前节点的数字信息复制到一个数组中
for (int j = 0; j < ROW; j++)
for (int k = 0; k < COL; k++)
b[j][k] = this->num[j][k];
int tmp = b[xi][yi];
b[this->zeroRow][this->zeroCol] = tmp;
b[xi][yi] = 0;
State succ(b);
succ.setG(this->g + 1);
succ.setF();
ret.push_back(succ);
}
}
return ret;
}
void State::showState()
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
if (num[i][j] == 0)
cout << ' ' << ' ';
else
cout << num[i][j] << ' ';
}
cout << endl;
}
cout << endl;
}
int State::getF()
{
return this->f;
}
int State::getG()
{
return this->g;
}
int State::getH()
{
return this->h;
}