BZOJ1085 SCOI2005 骑士精神 IDA*

题意:(没图不好说……)

题解:估价函数为当前状态与目标状态不同的格子数的数量-1

#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <climits>
#include <iostream>
#include <algorithm>
using namespace std;

const int MAXN=5+2;
const int x[]={1,2,2,1,-1,-2,-2,-1};
const int y[]={2,1,-1,-2,-2,-1,1,2};
const char Target[6][7]={"000000","011111","001111","000*11","000001","000000"};
int T;
char a[MAXN][MAXN];
bool flag;

bool Check(int x,int y){
    if(x<=0 || y<=0) return 0;
    if(x>5 || y>5) return 0;
    return 1;
}

bool IDAstar(int deep,int maxdeep){
    int sx,sy,f=0;
    for(int i=1;i<=5;i++)
        for(int j=1;j<=5;j++){
            if(a[i][j]=='*') sx=i,sy=j;
            f+=(a[i][j]!=Target[i][j]);
        }

    if(!f) return 1;
    if(deep+f-1>maxdeep) return 0;

    for(int i=0;i<=7;i++)
        if(Check(sx+x[i],sy+y[i])){
            swap(a[sx][sy],a[sx+x[i]][sy+y[i]]);
            if(IDAstar(deep+1,maxdeep)) return 1;
            swap(a[sx][sy],a[sx+x[i]][sy+y[i]]);
        }

    return 0;
}

int main(){
    cin >> T;
    while(T--){
        for(int i=1;i<=5;i++)
            for(int j=1;j<=5;j++)
                cin >> a[i][j];

        flag=0;
        for(int i=0;i<=15 && !flag;i++)
            if(IDAstar(0,i)){
                flag=1;
                cout << i << endl;
            }
        if(!flag) cout << -1 << endl;
    }

    return 0;
}
View Code

 

posted @ 2017-02-28 00:59  WDZRMPCBIT  阅读(54)  评论(0编辑  收藏