Game III

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 31   Accepted Submission(s) : 11

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

Problem Description

Zjt and Sara will take part in a game, named Game III. Zjt and Sara will be in a maze, and Zjt must find Sara. There are some strang rules in this maze. If Zjt move a step, Sara will move a step in opposite direction.
Now give you the map , you shold find out the minimum steps, Zjt have to move. We say Zjt meet Sara, if they are in the same position or they are adjacent . 
Zjt can only move to a empty position int four diraction (up, left, right, down). At the same time, Sara will move to a position in opposite direction, if there is empty. Otherwise , she will not move to any position.
The map is a N*M two-dimensional array. The position Zjt stays now is marked Z, and the position, where Sara stays, is marked E.

>  . : empty position
>  X: the wall
>  Z: the position Zjt now stay
>  S: the position Sara now stay

Your task is to find out the minimum steps they meet each other.

Input

The input contains several test cases. Each test case starts with a line contains three number N ,M (2<= N <= 20, 2 <= M <= 20 ) indicate the size of the map. Then N lines follows, each line contains M character. A Z and a S will be in the map as the discription above.

Output

For each test case, you should print the minimum steps. “Bad Luck!” will be print, if they can't meet each other.

Sample Input

4 4
XXXX
.Z..
.XS.
XXXX
4 4
XXXX
.Z..
.X.S
XXXX
4 4
XXXX
.ZX.
.XS.
XXXX

Sample Output

1
1
Bad Luck!
#include <iostream>
#include <cstdio>
#include<cmath>
#include<queue>
#include<cstring>
using namespace std;
struct node
{
int x,y,u,v,ti;
node(int a,int b,int c,int d,int e){x=a;y=b;u=c;v=d;ti=e;}
};
int n,m,i,j,sx,sy,tx,ty,ans;
char mp[][];
int vis[][][][]; //标记走过否
int dr[][]={{,},{,-},{-,},{,} }; bool check(int x,int y)
{
if (x>= && x<n && y>= && y<m && mp[x][y]!='X') return ;
return ;
}
void bfs()
{
queue<node>Q;
vis[sx][sy][tx][ty]=;
Q.push(node(sx,sy,tx,ty,));
while(!Q.empty())
{
node p=Q.front();
Q.pop();
if (abs(p.x-p.u)+abs(p.y-p.v)<=) { ans=p.ti; return; }
for(i=;i<;i++)
{
int xx=p.x+dr[i][];
int yy=p.y+dr[i][];
int uu=p.u-dr[i][];
int vv=p.v-dr[i][];
if (check(xx,yy))
{
if (!check(uu,vv))
{
uu=p.u;
vv=p.v;
}
if (!vis[xx][yy][uu][vv])
{
vis[xx][yy][uu][vv]=;
Q.push(node(xx,yy,uu,vv,p.ti+));
}
}
}
}
return;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(i=;i<n;i++)
{
scanf("%s",&mp[i]);
for(j=;j<m;j++)
{
if (mp[i][j]=='Z') sx=i,sy=j;
if (mp[i][j]=='S') tx=i,ty=j;
}
}
ans=-;
memset(vis,,sizeof(vis));
bfs();
if (ans==-) printf("Bad Luck!\n");
else printf("%d\n",ans);
}
return ;
}
04-28 04:02