学习一发IDA*。
/* Pigonometry */
#include <cstdio>
#include <iostream>
using namespace std;
const int maxn = 4, maxm = 105, inf = 0x3f3f3f3f;
char opt[] = {'u', 'd', 'l', 'r'};
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
int mp[maxn][maxn], ed[maxn][maxn];
bool found;
char solu[maxm];
inline int read() {
char ch = getchar(); for(; !(ch == 'x' || (ch >= '0' && ch <= '9')); ch = getchar());
return ch == 'x' ? 0 : ch - '0';
}
inline int intabs(int x) {
return x < 0 ? -x : x;
}
inline int getH() {
int res = 0;
for(int i = 1; i <= 3; i++) for(int j = 1; j <= 3; j++) if(mp[i][j]) {
int x = (mp[i][j] - 1) / 3 + 1, y = (mp[i][j] - 1) % 3 + 1;
res += intabs(i - x) + intabs(j - y);
}
return res;
}
inline int dfs(int x, int y, int d, int lim) {
int h = getH();
if(h == 0 || found) {
found = 1;
return d;
}
if(d + h > lim) return d + h;
int nowlim = inf;
for(int i = 0; i < 4; i++) {
int xx = x + dx[i], yy = y + dy[i];
if(xx < 1 || xx > 3 || yy < 1 || yy > 3) continue;
swap(mp[x][y], mp[xx][yy]);
solu[d] = opt[i];
int nextlim = dfs(xx, yy, d + 1, lim);
nowlim = min(nowlim, nextlim);
if(found) return nowlim;
swap(mp[x][y], mp[xx][yy]);
}
return nowlim;
}
int main() {
int sx, sy;
for(int i = 1; i <= 3; i++) for(int j = 1; j <= 3; j++) {
mp[i][j] = read();
if(!mp[i][j]) sx = i, sy = j;
ed[i][j] = (i - 1) * 3 + j;
}
ed[3][3] = 0;
found = 0;
int deplim = getH();
while(deplim < 100 && !found) deplim = dfs(sx, sy, 0, deplim);
if(!found) printf("unsolvable\n");
else {
solu[deplim] = '\0';
printf("%s", solu);
}
return 0;
}