# [bzoj] 1085 骑士精神 || ID-DFS

### 原题

IDDFS（限制层数的dfs）即可

#include<cstdio>
#include<algorithm>
using namespace std;
int t,n,m,disx[10]={0,1,2,2,1,-1,-2,-2,-1},disy[10]={0,2,1,-1 ,-2,-2,-1,1,2},posx,posy,ans;
char a[8][8];

{
int ans=0,fu=1;
char j=getchar();
for (;(j<'0' || j>'9') && j!='-';j=getchar()) ;
if (j=='-') j=getchar(),fu=-1;
for (;j>='0' && j<='9';j=getchar()) ans*=10,ans+=j-'0';
return ans*fu;
}

int chk()
{
int cnt;
if (a[3][3]!='*') cnt=1;
for (int i=1;i<=5;i++)
for (int j=i+(i>=3);j<=5;j++)
if (a[i][j]=='0') cnt++;
for (int i=5;i>=1;i--)
for (int j=1;j<=i-(i<=3);j++)
if (a[i][j]=='1') cnt++;
return cnt;
}

bool check()
{
for (int i=1;i<=5;i++)
for (int j=i+(i>=3);j<=5;j++)
if (a[i][j]=='0') return 0;
for (int i=5;i>=1;i--)
for (int j=1;j<=i-(i<=3);j++)
if (a[i][j]=='1') return 0;
return 1;
}

bool illegal(int x,int y)
{
if (x<1 || y<1) return 1;
if (x>5 || y>5) return 1;
return 0;
}

void dfs(int x,int px,int py)
{
if (!x)
{
if (px==3 && py==3 && check()) ans=1;
return ;
}
for (int i=1;i<=8;i++)
{
int vx,vy;
vx=px+disx[i];
vy=py+disy[i];
if (illegal(vx,vy)) continue;
swap(a[vx][vy],a[px][py]);
if (chk()<=x) dfs(x-1,vx,vy);
swap(a[vx][vy],a[px][py]);
}
}

int main()
{
while (t--)
{
ans=0;
for (int i=1;i<=5;i++)
{
for (int j=1;j<=5;j++)
{
a[i][j]=getchar();
if (a[i][j]=='*') posx=i,posy=j;
}
getchar();
}
for (int i=0;i<=15;i++)
{
dfs(i,posx,posy);
if (ans)
{
printf("%d\n",i);
break;
}
}
if (!ans) printf("-1\n");
}
return 0;
}

posted @ 2017-12-10 22:42  Mrha  阅读(74)  评论(0编辑  收藏