【题目链接】
https://www.lydsy.com/JudgeOnline/problem.php?id=1085
【算法】
IDA*
【代码】
#include<bits/stdc++.h> using namespace std; const int dx[8] = {-2,-2,-1,-1,1,1,2,2}; const int dy[8] = {-1,1,-2,2,-2,2,-1,1}; const int goal[5][5] = { {1,1,1,1,1}, {0,1,1,1,1}, {0,0,2,1,1}, {0,0,0,0,1}, {0,0,0,0,0} }; int i,j,T,x,y,step; char c; bool solved; int mp[5][5]; inline bool valid(int x,int y) { return x >= 0 && x < 5 && y >= 0 && y < 5; } inline int f() { int i,j; int ret = 0; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { if (mp[i][j] != goal[i][j]) ret++; } } return ret - 1; } inline bool IDDFS(int dep,int x,int y) { int i,tx,ty; if (dep + f() > step) return false; if (dep == step) return true; for (i = 0; i < 8; i++) { tx = x + dx[i]; ty = y + dy[i]; if (valid(tx,ty)) { swap(mp[x][y],mp[tx][ty]); if (IDDFS(dep+1,tx,ty)) return true; swap(mp[x][y],mp[tx][ty]); } } return false; } int main() { scanf("%d",&T); getchar(); while (T--) { solved = false; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { c = getchar(); if (c == '0') mp[i][j] = 0; else if (c == '1') mp[i][j] = 1; else { x = i; y = j; mp[i][j] = 2; } } getchar(); } for (i = 0; i <= 15; i++) { step = i; if (IDDFS(0,x,y)) { printf("%d ",i); solved = true; break; } } if (!solved) printf("-1 "); } return 0; }