题目大意:
解题思路:
其实就相当于八数码难题把,估价函数都一样,感觉用A星也可以做,为了练习,还是用了IDA*
- 其实就多了判断当前剩余层次是否够用就行了
if (maxd + 1 - d < h(cur)) return false;
AC代码:
#include<bits/stdc++.h>
using namespace std;
char goal[10][10] = {{"11111"}, {"01111"}, {"00*11"}, {"00001"}, {"00000"}};
char cur[10][10];
int x[8] = {-1, -1, 1, 1, -2, -2, 2, 2}, y[8] = {-2, 2, -2, 2, 1, -1, 1, -1};
int T, maxd;
int h(char now[10][10]) {
int cnt = 0;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
if (now[i][j] != goal[i][j] && goal[i][j] != '*')
cnt++;
return cnt;
}
bool dfs(int d, int tx, int ty) {
if (d == maxd + 1) {
if (!h(cur)) return true;
else return false;
}
if (maxd + 1 - d < h(cur)) return false;
for (int i = 0, nx, ny; i < 8; i++) {
nx = tx + x[i], ny = ty + y[i];
if (nx < 0 || nx > 4 || ny < 0 || ny > 4) continue;
swap(cur[tx][ty], cur[nx][ny]);
if (dfs(d + 1, nx, ny)) {
return true;
}
swap(cur[nx][ny], cur[tx][ty]);
}
return false;
}
int main() {
cin >> T;
while (T--) {
int tx, ty;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++) {
cin >> cur[i][j];
if (cur[i][j] == '*') tx = i, ty = j;
}
bool ok = false;
for (maxd = 0; maxd <= 15; maxd++) {
if (dfs(1, tx, ty)) {
ok = true;
break;
}
}
if (ok) cout << maxd << endl;
else cout << -1 << endl;
}
}
/*
1
11111
01111
10010
00001
000*0
*/