【BZOJ1085】【SCOI2005】骑士精神 [A*搜索]

骑士精神

Time Limit: 10 Sec  Memory Limit: 162 MB
[Submit][Status][Discuss]

Description

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

  【BZOJ1085】【SCOI2005】骑士精神 [A*搜索]

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

HINT

  Ans<=15

Solution

  看到这题,我们没有什么思路,只能运用搜索,然后把错位的个数当做估价,跑一遍A*就可以了。

Code

#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
using namespace std;
typedef long long s64; const int ONE = ; int T;
int a[][],Step,Vx,Vy;
char ch[];
bool PD;
int dx[]={,,-,-,,,-,-};
int dy[]={,,,,-,-,-,-};
int Goal[][]=
{
{,,,,,},
{,,,,,},
{,,,,,},
{,,,,,},
{,,,,,},
{,,,,,}
}; inline int get()
{
int res=,Q=; char c;
while( (c=getchar())< || c>)
if(c=='-')Q=-;
if(Q) res=c-;
while((c=getchar())>= && c<=)
res=res*+c-;
return res*Q;
} int Evaluation()
{
int res = ;
for(int i=;i<=;i++)
for(int j=;j<=;j++)
if(a[i][j] != Goal[i][j])
res++;
return res;
} void Dfs(int T,int x,int y)
{
if(PD) return;
if(T == Step)
{
PD = !Evaluation();
return;
} for(int i=;i<;i++)
{
int Nx = x+dx[i], Ny = y+dy[i];
if(!(<=Nx && Nx<= && <=Ny && Ny<=)) continue;
swap(a[x][y], a[Nx][Ny]);
if(Evaluation() + T <= Step) Dfs(T+, Nx,Ny);
swap(a[x][y], a[Nx][Ny]);
}
} void Solve()
{
for(int i=;i<=;i++)
{
scanf("%s",ch+);
for(int j=;j<=;j++)
{
if(ch[j] == '*') {a[i][j] = , Vx=i,Vy=j;}
else a[i][j] = ch[j]-'';
}
} PD=;
for(Step=;Step<=;Step++)
{
Dfs(,Vx,Vy);
if(PD) break;
} printf("%d\n",PD== ? Step:-);
} int main()
{
T=get();
while(T--)
Solve();
}
上一篇:转://对于11gR2的集群relink


下一篇:python中os.path.isdir()等函数的作用和用法