题目链接
思路:
启发函数依旧是初始位置与目标位置之间的曼哈顿距离,可以用IDA* 迭代加深来做,题目让输出字典序最小的方案,所以我们可以按 d, l, r, u 搜索顺序即可,注意每次搜索要记录上次操作,避免进行与上次相反的操作
开始以为和八数码1的做法并没有区别,就按A* 来做一直T,结果换成IDA* 就过了
代码
#include <bits/stdc++.h>
#define fi first
#define se second
#define fast ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
typedef pair<int, string>PIS;
typedef pair<string, char>PSC;
typedef pair<int, int>PII;
int dx[] = {1, 0, 0, -1}, dy[] = {0, -1, 1, 0};
string op = {"dlru"};
char ans[500];
int g[5][5], to[5][5];
int f(){
int sum = 0;
for (int i = 0; i < 3; i ++){
for (int j = 0; j < 3; j ++){
int num = g[i][j];
if (!num) continue;
sum += abs(to[num][0] - i) + abs(to[num][1] - j);
}
}
return sum;
}
bool dfs(int u, int max_depth, int sx, int sy, int pre, int cnt){
if (u + f() > max_depth) return false;
if (f() == 0){
cout << cnt << endl;
cout << ans << endl;
return true;
}
for (int i = 0; i < 4; i ++){
int x = sx + dx[i], y = sy + dy[i];
if (x < 0 || x >= 3 || y < 0 || y >= 3) continue;
if (pre + i == 3) continue;
swap(g[sx][sy], g[x][y]);
ans[cnt] = op[i];
if (dfs(u + 1, max_depth, x, y, i, cnt + 1)) return true;
swap(g[sx][sy], g[x][y]);
ans[cnt] = 0;
}
return false;
}
int main(){
fast;
int T;
cin >> T;
for (int cas = 1; cas <= T; cas ++){
cout << "Case " << cas << ": ";
string ed, start;
memset(ans, 0, sizeof(ans));
memset(g, 0, sizeof(g));
memset(to, 0, sizeof(to));
cin >> start >> ed;
int x, y;
for (int i = 0; i < 9; i ++){
if (start[i] == 'X') x = i / 3, y = i % 3, g[i / 3][i % 3] = 0;
else g[i / 3][i % 3] = start[i] - '0';
}
for (int i = 0; i < 9; i ++){
if (ed[i] == 'X') continue;
to[ed[i] - '0'][0] = i / 3;
to[ed[i] - '0'][1] = i % 3;
}
int depth = 0;
while(!dfs(0, depth, x, y, -1, 0)) depth++;
}
return 0;
}