BZOJ1085 [SCOI2005]骑士精神

本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作。

本文作者:ljh2000
作者博客:http://www.cnblogs.com/ljh2000-jump/
转载请注明出处,侵权必究,保留最终解释权!

 

Description

  在一个5×5的棋盘上有12个白色的骑士和12个黑色的骑士, 且有一个空位。在任何时候一个骑士都能按照骑
士的走法(它可以走到和它横坐标相差为1,纵坐标相差为2或者横坐标相差为2,纵坐标相差为1的格子)移动到空
位上。 给定一个初始的棋盘,怎样才能经过移动变成如下目标棋盘: 为了体现出骑士精神,他们必须以最少的步
数完成任务。

Input

  第一行有一个正整数T(T<=10),表示一共有N组数据。接下来有T个5×5的矩阵,0表示白色骑士,1表示黑色骑
士,*表示空位。两组数据之间没有空行。

Output

  对于每组数据都输出一行。如果能在15步以内(包括15步)到达目标状态,则输出步数,否则输出-1。

Sample Input

2
10110
01*11
10111
01001
00000
01011
110*1
01110
01010
00100

Sample Output

7
-1

 

 

正解:A*算法+迭代加深搜索

解题报告:

  直接迭代加深搜索肯定T飞...

  考虑优化,首先如果当前状态与目标状态相比,有大量的元素不在其本来位置上则可以直接剪枝。即已经操作的步数+不在其位置上的数>当前上限,则剪枝。

  A*算法的简单运用。

 

//It is made by ljh2000
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long LL;
int ans,d,a[7][7],yi[12][2]={{},{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
bool ok;
char ch[7][7];
int belong[7][7]={{},
	{0,2,2,2,2,2},
	{0,1,2,2,2,2},
	{0,1,1,3,2,2},
	{0,1,1,1,1,2},
	{0,1,1,1,1,1},
};
inline int getint(){
    int w=0,q=0; char c=getchar(); while((c<'0'||c>'9') && c!='-') c=getchar();
    if(c=='-') q=1,c=getchar(); while (c>='0'&&c<='9') w=w*10+c-'0',c=getchar(); return q?-w:w;
}
inline bool check(int s[7][7]){ for(int i=1;i<=5;i++) for(int j=1;j<=5;j++) if(s[i][j]!=belong[i][j]) return false;	return true;}
inline bool go_on(int hav,int s[7][7]){ 
	int tot=0;
	for(int i=1;i<=5;i++) for(int j=1;j<=5;j++) if(s[i][j]!=belong[i][j]) { tot++; if(tot+hav>d) return false; } 
	return true;
}

inline void dfs(int step,int s[7][7],int posx,int posy,int last){
	if(posx==3 && posy==3) { if(check(s)) { ok=true; return; } }
	if(step==d) return ; int fromx,fromy; int ss[7][7];
	for(int i=1;i<=5;i++) for(int j=1;j<=5;j++) ss[i][j]=s[i][j];
	
	for(int i=1;i<=8;i++) {
		if(last+i==9) continue;
		fromx=posx+yi[i][0]; if(fromx<=0 || fromx>5) continue;
		fromy=posy+yi[i][1]; if(fromy<=0 || fromy>5) continue;
		swap(ss[fromx][fromy],ss[posx][posy]);
		if(go_on(step,ss)) { dfs(step+1,ss,fromx,fromy,i); if(ok) return ; }
		swap(ss[fromx][fromy],ss[posx][posy]);
	}
}

inline void work(){
	int T=getint();
	while(T--) {
		for(int i=1;i<=5;i++) scanf("%s",ch[i]+1);
		ans=16;	int tarx=-1,tary=-1; ok=false;
		for(int i=1;i<=5;i++) for(int j=1;j<=5;j++) { if(ch[i][j]=='*') { tarx=i,tary=j; a[i][j]=3;} else a[i][j]=ch[i][j]-'0'+1;  }
		if(check(a)) { printf("0
"); continue; } 
		for(d=1;d<=15;d++) {
			dfs(0,a,tarx,tary,-1);
			if(ok) { ans=d; break; }
		}
		if(ans==16) printf("-1
");
		else printf("%d
",ans);
	}
}

int main()
{
    work();
    return 0;
}

  

原文地址:https://www.cnblogs.com/ljh2000-jump/p/6264028.html