求助
#define jiasu ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#include <bits/stdc++.h>
using namespace std;
int n, sx, sy, ans;
int dx[8] = {-2, -2, -1, 1, -1, 1, 2, 2};
int dy[8] = {-1, 1, 2, 2, -2, -2, -1, 1};
char mp[7][7];
//目标状态
char goal[7][7] = {{0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1}, {0, 0, 1, 1, 1, 1},
{0, 0, 0, 2, 1, 1}, {0, 0, 0, 0, 0, 1}, {0, 0, 0, 0, 0, 0}};
int f() {
int cnt = 0;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (mp[i][j] != goal[i][j])
cnt++;
}
}
return cnt;
}
void IDA_STAR(int k, int maxn, int x, int y, int last) { //已经走了k步
if (k == maxn) {
if (f() == 0) {
ans = k;
cout << ans << endl;
}
return;
}
for (int i = 0; i < 8; i++) {
if (i == 7 - last) //避免走和上一步相反的
continue;
int newx = x + dx[i];
int newy = y + dy[i];
if (newx < 1 || newx > 5 || newy < 1 || newy > 5)
continue;
if (f() + k > maxn)
continue;
swap(mp[x][y], mp[newx][newy]);
IDA_STAR(k + 1, maxn, newx, newy, i);
swap(mp[x][y], mp[newx][newy]);
}
}
int main() {
jiasu;
cin >> n;
while (n--) {
for (int i = 1; i <= 5; i++) {
char c;
for (int j = 1; j <= 5; j++) {
cin >> c;
if (c == '*') { //将*标记为2
sx = i, sy = j;
mp[i][j] = 2;
continue;
}
mp[i][j] = c - '0';
}
}
if (!f()) { //直接就是目标状态
cout << 0 << endl;
continue;
}
int maxn = 1;
while (maxn <= 15) { //不断增加步数
ans = -1;
IDA_STAR(0, maxn, sx, sy, -1);
maxn++;
if (ans != -1)
break;
}
if (maxn <= 15)
cout << ans << endl;
else
cout << "-1" << endl;
}
system("pause");
return 0;
}