ida*-洛谷P2324 [SCOI2005] 骑士精神

https://daniu.luogu.org/problem/show?pid=2324
就是a*;
然后我dfs写炸了;
唉~~;

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#define Ll long long
using namespace std;
int cc[6][6]{
{9,9,9,9,9,9},
{9,1,1,1,1,1},
{9,0,1,1,1,1},
{9,0,0,9,1,1},
{9,0,0,0,0,1},
{9,0,0,0,0,0}
};
int xx[8]{1,1,-1,-1,2,-2,2,-2};
int yy[8]{2,-2,2,-2,1,-1,-1,1};
int a[6][6];
int m,X,Y,ans;
char c;
int H(){
    int ans=0;
    for(int i=1;i<=5;i++)
    for(int j=1;j<=5;j++)
    if(a[i][j]!=cc[i][j])ans++;
    if(a[3][3]!=9)return ans-1;
    return ans;
}
void dfs(int X,int Y,int g,int tf){
    int h=H();
    if(!h){ans=g;return;}
    if(g==tf||ans>=0||h+g>tf)return;
    for(int i=0;i<8;i++){
        int x=X+xx[i];
        int y=Y+yy[i];
        if(x>0&&y>0&&x<6&&y<6){//这个地方比较危险 
            swap(a[x][y],a[X][Y]);
            dfs(x,y,g+1,tf);
            swap(a[x][y],a[X][Y]);
}}}
int main()
{
    scanf("%d",&m);
while(m--){
    ans=-1;//ans一开始不可以为0,因为0也可能是答案 
    for(int i=1;i<=5;i++)
    for(int j=1;j<=5;j++){
        cin>>c;
        if(c=='1')a[i][j]=1;else
        if(c=='*')X=i,Y=j,a[i][j]=9;else
        a[i][j]=0;
    }
    for(int i=0;i<=15;i++){
        dfs(X,Y,0,i);
        if(ans>=0)break;
    }
    printf("%d\n",ans);
}}
posted @ 2017-03-24 08:46  largecube233  阅读(111)  评论(0编辑  收藏  举报