八数码问题

题目简述

也没啥好简述的,去看洛谷吧。

解题思路

没啥好方法,爆搜得了。

当然考场上不能这么自暴自弃,考虑优化。


定义估价函数 h(x) 为当前所有数字到它本应在的位置的曼哈顿距离(空格不算!)
然后直接套 IDA* 模板做四向搜索就可以了

代码实现

这里给出的写法是字符串存二维数组,比较简洁

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
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>

#define DEBUG(x) std::cerr << #x << " = " << x << std::endl;
#define mp std::make_pair
#define coo std::pair<int, int>
#define itoxy(i) mp(i/3, i%3);
#define xytoi(xy) (xy.first * 3 + xy.second)
#define dist(x,y) (std::abs(x.first - y.first) + std::abs(x.second - y.second))

using std::cin;
using std::cout;
using std::endl;

inline int read() {
int s = 0, x = 1; char ch = getchar();
while (!isdigit(ch)) { if (ch == '-') x = -x; ch = getchar(); }
while (isdigit(ch)) { s = s * 10 + ch - '0'; ch = getchar(); }
return s * x;
}

const std::string end = "123804765";
const int dx[] = { 0, 0, 0, 1, -1 };
const int dy[] = { 0, 1, -1, 0, 0 };

std::string start;
bool success = false;

int h() {
int ret = 0;
for (int x = 0; x < 3; ++x) {
for (int y = 0; y < 3; ++y) {
coo st = mp(x, y);
int pos = xytoi(st);
if (start[pos] == '0') continue;
coo ed = itoxy(end.find(start[pos]));
ret += dist(st, ed);
}
}
return ret;
}

void search(int step, int maxdep, int last0) {
int hx = h();
if (hx == 0 || success) {
success = true; return;
}
if (step + hx > maxdep) return;
int p0 = start.find('0'); coo t = itoxy(p0);
for (int dir = 1; dir <= 4; ++dir) {
coo now = mp(t.first + dx[dir], t.second + dy[dir]);
int pnow = xytoi(now);
if (now.first < 0 || now.first > 2
|| now.second < 0 || now.second > 2 || pnow == last0)
continue;
std::swap(start[pnow], start[p0]);
search(step + 1, maxdep, p0);
if (success) return;
std::swap(start[pnow], start[p0]);
}
}

int main() {
cin >> start;
if (start == end) {
cout << 0 << endl;
return 0;
}
int maxdep = 1;
while (!success) {
search(1, maxdep, -1);
if (!success) ++maxdep;
}
printf("%d\n", maxdep - 1);
return 0;
}