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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _15probe
{
class Program
{
static void Main(string[] args)
{
#region переменные
int[] dx = new int[] { 0, -1, 0, 1 };//смещения пустой клетки
int[] dy = new int[] { 1, 0, -1, 0 };
//var moveDescription:Array = new Array("D", "L", "U", "R"); }
char[] move_desc = new char[] { 'D', 'L', 'U', 'R' };// Возможные ходы
int[] opposite_move = new int[] { 2, 3, 0, 1 };// Противоположные ходы (2, 3, 0, 1)
//var oppositeMove:Array = new Array(2, 3, 0, 1); }
const int infinity = 10000;
//int x0, // координаты пустой клетки
// y0; // координаты пустой клетки
int[] goalX = new int[16]; //goalX[i] - координата x i-й пятнашки, ...
int[] goalY = new int[16];
int[,] board = new int[,] { { 1, 2, 3, 4 }, { 5, 7, 12, 11 }, { 10, 0, 6, 8 }, { 9, 13, 14, 15 } };
//int[,] board = new int[,] { { 2, 5, 4, 6 }, { 1, 13, 11, 3 },
// { 14, 12, 7, 10 }, { 8, 15, 9, 0 } }; // доска
//int step;
int[,] boardGoal = new int[4, 4]; // доска целевого состояния
int minPrevIteration; //deepness; // глубина
//string resultString; //результат
//минимум стоимости среди нерассмотренных узлов
#endregion
//--------------------------------
//инициализирует целевое состояние
void initGoalArrays()
{
for (int i = 0; i < 15; i++)
{
goalX[i + 1] = i % 4;
goalY[i + 1] = i / 4;
goalX[0] = 4;
goalY[0] = 4;
}
}
//меняет местами две пятнашки
void swap(int y1, int x1, int y2, int x2)
{
int value1, value2;
value1 = board[y1, x1];
value2 = board[y2, x2];
board[y1, x1] = value2;
board[y2, x2] = value1;
}
//определяет "решаемость" пятнашек
bool isSolvable()
{
int count, transpos, value, i, j;
count = 0;
transpos = 0;
value = 0;
int[] a = new int[16];
for (i = 0; i < 4; i++)
{
if (i % 2 == 0)
{
for (j = 0; j < 4; j++)
{
value = board[i, j];
if (value > 0)
{
a[count] = value;
count++;
}
}
}
else
{
for (j = 3; j >= 0; j--)
{
value = board[i, j];
if (value > 0)
{
a[count] = value;
count++;
}
}
}
}
for (i = 0; i <= count - 2; i++)
for (j = i + 1; j <= count - 1; j++)
if (a[i] > a[j])
transpos++;
if (transpos % 2 == 1)
return true;
return false;
}
//718508644774274130
//10446283839894545490
//эвристическая оценочная функция Манхеттеновское расстояние
void estimate(out int manhattan)
{
int i, j, value, m;
manhattan = 0;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
value = board[i, j];
if (value > 0)
{
m = Math.Abs(i - goalY[value]) + Math.Abs(j - goalX[value]);
manhattan = manhattan + m;
}
}
}
}
//поиск в глубину с обрезанием f=g+h < deepness
void recSearch(int g, int previousMove, int x0, int y0, int step, int deepness, out bool tf,
out string resultString)
{
int h;
int manhattan;
estimate(out manhattan);
h = manhattan;
tf = false;
resultString = null;
step = 0;
// h = минимум ходов к цели
if (h == 0)
{
tf = true;
return; // если это цель - ура!
}
// если то, что мы прошли (g) + то, что нам как минимум осталось (h)
// больше допустимой глубины - выход.
int f;
f = g + h;
if (f > deepness)
{
//нaходим минимум стоимости среди "обрезаных" узлов
if (minPrevIteration > f)
minPrevIteration = f;
return;
}
int newx, newy;
bool res;
// делаем всевозможные ходы
for (int i = 0; i < 4; i++)
{
if (opposite_move[i] != previousMove)
{
// новые координаты пустой клетки
newx = x0 + dx[i];
newy = y0 + dy[i];
if ((newy <= 3) && (newy >= 0) && (newx <= 3) && (newx >= 0))
{
swap(y0, x0, newy, newx); // двигаем пустую клетку на новое место
recSearch(g + 1, i, newx, newy, step, deepness, out tf, out resultString); // рекурсивный поиск с новой позиции
res = tf;
swap(y0, x0, newy, newx); // возвращаем пустую клетку назад
if (res == true) //если было найдено решение
{
resultString = move_desc[i] + resultString; //записываем этот ход
step++;
tf = true;
return; // и выходим
}
}
}
}
return; //цели не нашли
}
//итерация глубины и IDA*
bool idaStar(out string result)
{
bool res;
int x0 = -1;
int y0 = -1;
bool tf;
int step;
string resultString;
res = false;
result = null;
int manhattan;
estimate(out manhattan);
int deepness = manhattan; // начинаем с h для начального состояния
while (deepness <= 50)
{
minPrevIteration = infinity; // инициализация для поиска минимума
// поиск пустой клетки
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (board[i, j] == 0)
{
x0 = j;
y0 = i;
}
}
}
step = 0;
recSearch(0, -1, x0, y0, step, deepness, out tf, out resultString);
deepness = minPrevIteration;
res = tf;
if (res)
{
result = resultString;
// ULURULDRDLLUULDRRDDLLURRDRULDLLURRDRULURDLDR
break;
}
}
return res;
}
// ----------------------------
initGoalArrays();
// Целевая доска
int zn = 1;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
boardGoal[i, j] = zn;
zn++;
}
}
boardGoal[3, 3] = 0;
int manhat;
estimate(out manhat);
if (!isSolvable()) // если задача нерешаема
{
Console.WriteLine("Задача неразрешима");
return;
}
if (manhat == 0) //если это уже цель
{
Console.WriteLine("Это уже цель");
return;
}
//делаем IDA* поиск
string finalresult;
idaStar(out finalresult);
//recSearch(0, -1, 0, 0, out tf, out step, out resultString);
//Console.WriteLine("Количество ходов:", step);
if (finalresult == null)
{
Console.WriteLine("IDA* failed");
return;
}
else
{
Console.WriteLine("Путь:" + finalresult); //выводим результат
Console.ReadKey();
return;
}
}
}
} |