Game III
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 1285 Accepted Submission(s): 362
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.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<math.h>
using namespace std;
#define M 30
int maze[M][M][M][M];
char map[M][M];
int n,m,sx,sy,ex,ey;
struct node
{
int ax,ay;
int bx,by;
int step;
}ua,ub;
int dir[8][2]={{1,0},{-1,0},{0,1},{0,-1},{-1,0},{1,0},{0,-1},{0,1}};
int judge(node a)
{
int x,y;
x=fabs(a.bx-a.ax);
y=fabs(a.by-a.ay);
if(x+y<2)
return 1;
else
return 0;
}
int check(int a,int b)
{
if(a>=0&&a<n&&b>=0&&b<m&&map[a][b]!='X')
return 1;
return 0;
}
int bfs()
{
queue<node>q;
int x1,y1,x2,y2;
int i,j;
memset(maze,0,sizeof(maze));
ua.ax=sx;
ua.ay=sy;
ua.bx=ex;
ua.by=ey;
ua.step=0;
maze[sx][sy][ex][ey]=1;//以兩點的位置作爲標記,一旦走過就不再走了
q.push(ua);
while(!q.empty())
{
ua=q.front();
q.pop();
if(judge(ua))
{
return ua.step;
}
for(i=0;i<4;i++)
{
ub=ua;
ub.ax=ub.ax+dir[i][0];
ub.ay=ub.ay+dir[i][1];
ub.step++;
//z節點走到了某一個位置,下面判斷是否符合條件。
if(check(ub.ax,ub.ay))//現在z所在的點符合了條件
{
if(check(ub.bx+dir[i+4][0],ub.by+dir[i+4][1]))
{//s點進行了移動,進行計算標記
ub.bx=ub.bx+dir[i+4][0];
ub.by=ub.by+dir[i+4][1];
if(maze[ub.ax][ub.ay][ub.bx][ub.by]==0)
{
maze[ub.ax][ub.ay][ub.bx][ub.by]=1;
q.push(ub);
}
}
else
{//s點沒有進行移動,但是目前的情況仍舊未曾發生過即可。
if(maze[ub.ax][ub.ay][ub.bx][ub.by]==0)
{
maze[ub.ax][ub.ay][ub.bx][ub.by]=1;
q.push(ub);
}
}
}
}
}
return -1;
}
int main()
{
int i,j,k;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=0;i<n;i++)
{
scanf("%s",&map[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(map[i][j]=='Z')
{
sx=i;
sy=j;
}
else
if(map[i][j]=='S')
{
ex=i;
ey=j;
}
}
}
int ans=bfs();
if(ans!=-1)
{
printf("%d\n",ans);
}
else
{
printf("Bad Luck!\n");
}
}
return 0;
}