[BZOJ 1085][SCOI 2005]骑士精神(IDA*搜索)

题目链接:http://www.lydsy.com:808/JudgeOnline/problem.php?id=1085

考虑到深度不超过15,IDA*搜索可做。

估价函数h()=当前不在目标位置的棋子个数。

然后其他细节就和普通的迭代加深一样了。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>

using namespace std;

int xx[]={1,1,-1,-1,2,2,-2,-2};
int yy[]={2,-2,2,-2,1,-1,1,-1};
char map[6][6];
char goal[6][6]={
    {0,0,0,0,0,0},
    {0,'1','1','1','1','1'},
    {0,'0','1','1','1','1'},
    {0,'0','0','*','1','1'},
    {0,'0','0','0','0','1'},
    {0,'0','0','0','0','0'}
}; //目标棋盘

bool inMap(int x,int y)
{
    if(x<1||x>5||y<1||y>5) return false;
    return true;
}

int h() //估价函数
{
    int ans=0;
    for(int i=1;i<=5;i++)
        for(int j=1;j<=5;j++)
            ans+=(goal[i][j]!=map[i][j]);
    return ans;
}

bool IDAstar(int step,int maxdeep)
{
    if(step>maxdeep) return false;
    int predict=h(),bx,by; //空格坐标为(bx,by)
    if(!predict) return true; //达到目标状态
    if(predict-1+step>maxdeep) return false; //h()函数剪枝
    for(int i=1;i<=5;i++)
        for(int j=1;j<=5;j++)
            if(map[i][j]=='*')
                bx=i,by=j;
    for(int dir=0;dir<8;dir++)
    {
        int tx=bx+xx[dir],ty=by+yy[dir];
        if(!inMap(tx,ty)) continue;
        swap(map[bx][by],map[tx][ty]);
        if(IDAstar(step+1,maxdeep)) return true;
        swap(map[bx][by],map[tx][ty]);
    }
    return false;
}

int main()
{
    int T,maxdeep;
    scanf("%d",&T);
    while(T--)
    {
        for(int i=1;i<=5;i++)
            scanf("%s",map[i]+1);
        for(maxdeep=0;maxdeep<=15;maxdeep++)
        {
            if(IDAstar(0,maxdeep))
            {
                printf("%d\n",maxdeep);
                break;
            }
        }
        if(maxdeep>15) puts("-1");
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值