BZOJ1085 [SCOI2005]骑士精神

一开始打了个爆搜,然后心里不稳网上一看,原来果然是A*

这段代码是迭代加深搜加A*的

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
const int dx[]={-2,-1,1,2,2,1,-1,-2};
const int dy[]={-1,-2,-2,-1,1,2,2,1};
char s[9];
int T,ok,x,y,k,a[5][5];
int goal[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}};
  
bool okk(int dep){
    int cnt=0;
    for(int i=0;i<5;i++){
    	for(int j=0;j<5;j++){
    		if(a[i][j]!=goal[i][j]){
        		cnt++;
        		if(cnt+dep>k){
        			return false;
				}
    		}	
		}
	}
    return true;
}
void dfs(int dep,int x,int y){
    if(dep==k&&!memcmp(a,goal,sizeof a)){
		ok=1;
		return;
	}
    for(int i=0;i<8;i++){
    	if(!ok&&dep<k){
			int xx=x+dx[i],yy=y+dy[i];
        	if(xx>=0&&xx<5&&yy>=0&&yy<5){
            	swap(a[x][y],a[xx][yy]);
            	if(okk(dep)){
            		dfs(dep+1,xx,yy);
				}
            	swap(a[x][y],a[xx][yy]);
        	}
		}
	}
}
int main(){
    cin>>T;
    while(T--){
        for(int i=0;i<5;i++){
            scanf("%s",s);
            for(int j=0;j<5;j++){
            	if(s[j]=='*'){
            		x=i,y=j,a[i][j]=2;
				}else{
					a[i][j]=s[j]-'0';
				}
			}
        }
        ok=0;
        for(k=0;k<=15;k++){
            dfs(0,x,y);
            if(ok){
				printf("%d\n", k);break;
			}
        }
        if(!ok){
        	cout<<-1<<endl;
		}
    }
    return 0;
}
/*
2
10110
01*11
10111
01001
00000

01011
110*1
01110
01010
00100
*/

/*
7
-1
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值