题目描述:
题目背景: SCOI2005 DAY2 T1
题目链接:bzoj 1085 骑士精神
在一个 5×5 的棋盘上有12个白色的骑士和 12 个黑色的骑士, 且有一个空位。在任何时候一个骑士都能按照骑士的走法(它可以走到和它横坐标相差为 1 ,纵坐标相差为 2 或者横坐标相差为 2 ,纵坐标相差为 1 的格子)移动到空位上。
给定一个初始的棋盘,怎样才能经过移动变成如下目标棋盘:
为了体现出骑士精神,他们必须以最少的步数完成任务。
输入格式:
第一行有一个正整数 T(T≤10),表示一共有 N 组数据。
接下来有 T 个 5×5 的矩阵,0 表示白色骑士,1 表示黑色骑士,* 表示空位。两组数据之间没有空行。
输出格式:
对于每组数据都输出一行。如果能在 15 步以内(包括 15 步)到达目标状态,则输出步数,否则输出 -1 。
样例输入:
2
10110
01*11
10111
01001
00000
01011
110*1
01110
01010
00100
样例输出:
7
-1
样例说明
样例中第二个数据的初始情况对应该图:
题目分析:
显然单纯的dfs和bfs是不行的。这道题可以直接A*剪枝就过。同时也可以迭代加深+A*剪枝过,速度更快。下附代码是迭代加深+A*剪枝。
附代码:
#include<iostream>
#include<cstring>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<ctime>
#include<cmath>
#include<cctype>
#include<iomanip>
#include<algorithm>
#include<queue>
using namespace std;
int t,ans,pox,poy;
char s[10][10];
bool check;
const int fx[9]={0,-1,-1,1,1,-2,-2,2,2};
const int fy[9]={0,2,-2,2,-2,1,-1,1,-1};
const char bz[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',};
int pd()//估价函数,有tot个不同,则至少需要tot-1步
{
int tot=-1;
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
if(bz[i][j]!=s[i][j]) tot++;
return tot;
}
void dfs(int x,int y,int num)
{
int left=pd();
if(left==-1) {check=true;return;}
if(num+left>ans) return;
for(int i=1;i<=8;i++)
{
int x1=x+fx[i];
int y1=y+fy[i];
if(x1>=1&&x1<=5&&y1>=1&&y1<=5)
{
swap(s[x1][y1],s[x][y]);
dfs(x1,y1,num+1);
if(check==true) return;
swap(s[x1][y1],s[x][y]);
}
}
}
int main()
{
//freopen("lx.in","r",stdin);
scanf("%d\n",&t);
while(t--)
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
s[i][j]=getchar();
if(s[i][j]=='*') {pox=i;poy=j;}
}
getchar();
}
check=false;
ans=pd();
if(ans==-1) {ans=0;check=true;}
while(ans<=15)
{
dfs(pox,poy,0);
if(check==true) break;
ans++;
}
if(check==false) printf("-1\n");
else printf("%d\n",ans);
}
return 0;
}