迷宫问题 | ||||||
| ||||||
Description | ||||||
小z身处在一个迷宫中,小z每分钟可以走到上下左右四个方向的相邻格之一。迷宫中有一些墙和障碍物。 同时迷宫中也有一些传送门,当小z走到任意一个传送门时,可以选择传送到其他任意的传送门(传送是不花费时间的), 当然也可以停留在原地。现在小z想知道走出迷宫需要花费的最少时间。 | ||||||
Input | ||||||
输入第一行为组数T(t<=10)。 对于每组数据第一行为两个整数R和C(1<=R,C<=100)。以下R行每行有C个字符,即迷宫地图。 其中"#"代表墙和障碍物,"."表示空地,"P"表示传送门,"Z"表示小z的起始位置,"W"表示迷宫出口。 对于每组数据保证起始位置和迷宫出口唯一。 | ||||||
Output | ||||||
对于每组数据,输出走出迷宫的最短时间(单位:分钟)。如果无法走出迷宫则输出"IMPOSSIBLE"。 | ||||||
Sample Input | ||||||
2 3 4 .Z.. .P#. ##PW 4 4 Z..P .... ##.. W#.P | ||||||
Sample Output | ||||||
2 IMPOSSIBLE | ||||||
Author | ||||||
陈禹@HRBUST |
#include<queue>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char maps[1003][1003];
int vis[1003][1003];
int n,m;
int door[10003][2];
int dnum=0;
int sx,sy;
struct data
{
int x,y;
int step;
};
int dx[4]= {0,0,1,-1};
int dy[4]= {1,-1,0,0};
int bfs(int x,int y)
{
data f,s,now;
queue<data>q;
f.x=x;
f.y=y;
f.step=0;
vis[f.x][f.y]=1;
q.push(f);
while(!q.empty())
{
s=q.front();
q.pop();
if(maps[s.x][s.y]=='W')
return s.step;
for(int i=0; i<4; i++)
{
now=s;
now.x+=dx[i];
now.y+=dy[i];
now.step=s.step+1;
if(now.x>0&&now.x<=n&&now.y>0&&now.y<=m&&maps[now.x][now.y]!='#'&&vis[now.x][now.y]==0)
{
if(maps[now.x][now.y]=='P')
{
for(int j=0; j<dnum; j++)
{
data z;
z.x=door[j][0];
z.y=door[j][1];
z.step=now.step;
q.push(z);
vis[z.x][z.y]=1;
}
}else q.push(now);
vis[now.x][now.y]=1;
}
}
}
return -1;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(vis,0,sizeof(vis));
dnum=0;
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++)
{
scanf("%s",maps[i]+1);
for(int j=1; j<=m; j++)
{
if(maps[i][j]=='Z')
{
sx=i;
sy=j;
}
if(maps[i][j]=='P')
{
door[dnum][0]=i;
door[dnum][1]=j;
dnum++;
}
}
}
int ans=bfs(sx,sy);
if(ans==-1)
printf("IMPOSSIBLE\n");
else printf("%d\n",ans);
}
}