bzoj 1085: [SCOI2005]骑士精神 IDA*
给一个图, 目标位置是确定的, 问你能否在15步之内达到目标位置。
因为只有15步, 所以直接ida*
#include<bits/stdc++.h> using namespace std; #define pb(x) push_back(x) #define ll long long #define mk(x, y) make_pair(x, y) #define lson l, m, rt<<1 #define mem(a) memset(a, 0, sizeof(a)) #define rson m+1, r, rt<<1|1 #define mem1(a) memset(a, -1, sizeof(a)) #define mem2(a) memset(a, 0x3f, sizeof(a)) #define rep(i, a, n) for(int i = a; i<n; i++) #define ull unsigned long long typedef pair<int, int> pll; const double PI = acos(-1.0); const double eps = 1e-8; const int mod = 1e9+7; const int inf = 1061109567; const int dir[][2] = { {-1, 2}, {1, 2}, {2, -1}, {2, 1},{-1,-2},{-2,-1},{-2,1},{1,-2} }; int ans[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 a[5][5], flag; int judge() { for(int i = 0; i<5; i++) { for(int j = 0; j<5; j++) { if(a[i][j]!=ans[i][j]) return 0; } } return 1; } int h() { int ret = 0; for(int i = 0; i<5; i++) { for(int j = 0; j<5; j++) { if(ans[i][j]!=a[i][j]) ret++; } } return ret; } int step; int dfs(int d) { if(d==step) return judge(); for(int i = 0; i<5; i++) { for(int j = 0; j<5; j++) { if(a[i][j] == 2) { for(int k = 0; k<8; k++) { int x = i+dir[k][0]; int y = j+dir[k][1]; if(x<0||x>4||y<0||y>4) continue; swap(a[i][j], a[x][y]); if(d+h()<=step) if(dfs(d+1)) return 1; swap(a[i][j], a[x][y]); } } } } return 0; } int main() { int t; cin>>t; char s[6]; while(t--) { for(int i = 0; i<5; i++) { scanf("%s", s); for(int j = 0; j<5; j++) { if(s[j] == '*') a[i][j] = 2; else a[i][j] = s[j]-'0'; } } flag = 0; for(int i = 0; i<=15; i++) { step = i; if(dfs(0)) { printf("%d\n", i); flag = 1; break; } } if(!flag) cout<<"-1"<<endl; } return 0; }