BZOJ 1085 骑士精神 A star algorithm DFS

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int mmap[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}
};
const int nnext[8][2]= {
    {1,2},
    {2,1},
    {-1,2},
    {1,-2},
    {-2,1},
    {2,-1},
    {-1,-2},
    {-2,-1}
};
int T,ans;
bool flag;
bool A_star(int b[][5],int now) {
    int sum=0;
    for(int i=0; i<5; i++)
        for(int j=0; j<5; j++)
            if(b[i][j]^mmap[i][j]) {
                sum++;
                if(sum+now>ans)
                    return 0;
            }
    return 1;
}
bool check(int b[][5]) {
    for(int i=0; i<5; i++)
        for(int j=0; j<5; j++)
            if(b[i][j]^mmap[i][j])
                return 0;
    return 1;
}
void DFS(int b[][5],int x,int y,int step) {
    if(step==ans) {
        if(check(b))
            flag=1;
        return ;
    }
    for(int i=0; i<8; i++) {
        int nextx=x+nnext[i][0];
        int nexty=y+nnext[i][1];
        if(nextx<0||nexty<0||nextx>=5||nexty>=5)
            continue;
        swap(b[x][y],b[nextx][nexty]);
        if(A_star(b,step))
            DFS(b,nextx,nexty,step+1);
        swap(b[x][y],b[nextx][nexty]);
    }
}
int main(void) {
#ifndef ONLINE_JUDGE
    freopen("E:\\input.txt","r",stdin);
#endif
    ios::sync_with_stdio(false);
    cin>>T;
    while(T--) {
        int x,y,a[5][5];//记录map中空点的位置
        char ch;
        for(int i=0; i<5; i++)
            for(int j=0; j<5; j++) {
                cin>>ch;
                if(ch=='*')
                    a[i][j]=2,x=i,y=j;
                else
                    a[i][j]=ch-'0';
            }
        for(ans=0; ans<=15; ans++) {
            flag=0,DFS(a,x,y,0);
            if(flag)
                break;
        }
        if(ans>15)
            cout<<-1<<endl;
        else
            cout<<ans<<endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值