#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
char map[22][22];
int sx, sy, ex, ey, n, m;
int dx[]= {1,0,-1,0}, dy[]= {0,1,0,-1};
bool vis[22][22][22][22];
struct sta
{
sta(int a,int b,int c,int d,int e)
{
x1=a,y1=b,x2=c,y2=d,now=e;
}
sta() {};
int x1, y1;
int x2, y2;
int now;
} tmp;
bool can(int x,int y)
{
if(x<0||y<0||x>=n||y>=m)
return false;
return true;
}
int main()
{
int i, j, r1, r2;
queue<sta> q;
while(scanf("%d%d",&n,&m)!=EOF)
{
while(!q.empty()) q.pop();
for(i=0; i<n; i++)
{
scanf("%s",&map[i]);
for(j=0; j<m; j++)
{
if(map[i][j]=='Z')
sx=i, sy=j;
if(map[i][j]=='S')
ex=i, ey=j;
for(r1=0; r1<n; r1++)
for(r2=0; r2<m; r2++)
vis[i][j][r1][r2]=false;
}
}
int x1, y1, x2, y2, ans, now, nx, ny, tx, ty;
vis[sx][sy][ex][ey]=true;
bool flag=false;
q.push(sta(sx,sy,ex,ey,0));
while(!q.empty())
{
tmp=q.front();
q.pop();
x1=tmp.x1, y1=tmp.y1, x2=tmp.x2, y2=tmp.y2, now=tmp.now;
int ll=abs(x1-x2)+abs(y1-y2);
if(ll<2)
{
ans=now,flag=true;
}
if(flag) break;
for(i=0; i<4; i++)
{
nx=x1+dx[i], ny=y1+dy[i];
if(can(nx,ny)&&map[nx][ny]!='X')
{
tx=x2+dx[(i+2)%4], ty=y2+dy[(i+2)%4];
if(can(tx,ty)&&map[tx][ty]!='X')
{
if(!vis[nx][ny][tx][ty])
q.push(sta(nx,ny,tx,ty,now+1));
vis[nx][ny][tx][ty]=true;
}
else
{
if(!vis[nx][ny][x2][y2])
q.push(sta(nx,ny,x2,y2,now+1));
vis[nx][ny][x2][y2]=true;
}
}
}
}
if(flag)
printf("%d\n",ans);
else puts("Bad Luck!");
}
return 0;
}
转载于:https://www.cnblogs.com/ink-syk/p/3315181.html