# [SCOI2005][BZOJ1085] 骑士精神

## 1085: [SCOI2005]骑士精神

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

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

## Sample Output

7
-1

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int t,k,a[6][6];
bool flag;
char c;
int ans[6][6]=
{
{0,0,0,0,0,0},
{0,1,1,1,1,1},
{0,0,1,1,1,1},
{0,0,0,2,1,1},
{0,0,0,0,0,1},
{0,0,0,0,0,0}};
int dx[8]={1,1,-1,-1,2,2,-2,-2};
int dy[8]={2,-2,2,-2,1,-1,1,-1};
int pd(int d,int k)
{
int v=0;
for (int i=1;i<=5;i++)
for (int j=1;j<=5;j++)
if (a[i][j]!=ans[i][j])
{
v++;
if (v+d>k) return 0;
}
return 1;
}
int judge()
{
for (int i=1;i<=5;i++)
for (int j=1;j<=5;j++)
if (a[i][j]!=ans[i][j]) return 0;
return 1;
}
void Astar(int d,int x,int y)
{
int xx,yy;
if (d==k)
{
if (judge()) flag=1;
return;
}
if (flag) return;
for (int i=0;i<8;i++)
{
xx=x+dx[i];
yy=y+dy[i];
if (xx<1||xx>5||yy<1||yy>5) continue;
swap(a[xx][yy],a[x][y]);
if (pd(d,k)) Astar(d+1,xx,yy);
swap(a[xx][yy],a[x][y]);
}
}
int main()
{
scanf("%d",&t);
while(t--)
{
int x,y;
for (int i=1;i<=5;i++)
{
getchar();
for (int j=1;j<=5;j++)
{
c=getchar();
if (c=='*')
{
a[i][j]=2;
x=i;
y=j;
continue;
}
a[i][j]=c-'0';
}
}
flag=0;
for (k=1;k<=15;k++)
{
Astar(0,x,y);
if (flag)
{
printf("%d\n",k);
break;
}
}
if (!flag) printf("-1\n");
}
return 0;
}

posted @ 2015-07-11 08:43  ws_fqk  阅读(163)  评论(0编辑  收藏