从输出中可以看出箱子和人的移动相继输出,就可以想到是嵌套bfs,另外写的时候需要注意细节。
//
// main.cpp
// Richard
//
// Created by 邵金杰 on 16/8/26.
// Copyright © 2016年 邵金杰. All rights reserved.
//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=22;
char dir[5]="NSWE";
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
struct node{
int bx,by,px,py;
string path;
};
struct point{
int x,y;
string temp;
};
char map[maxn][maxn];
int vis[maxn][maxn][4],v[maxn][maxn];
int n,m;
bool isok(int x,int y)
{
return x<1||x>n||y<1||y>m||map[x][y]=='#';
}
string temp;
bool bfsman(int sx,int sy,int ex,int ey,int nx,int ny)
{
temp="";
memset(v,0,sizeof(v));
point state,now,next;
state.x=sx;
state.y=sy;
v[sx][sy]=1;
state.temp="";
queue<point> q;
q.push(state);
while(!q.empty())
{
now=q.front();
q.pop();
if(now.x==ex&&now.y==ey)
{
temp=now.temp;
return true;
}
for(int i=0;i<4;i++)
{
next=now;
next.x=now.x+dx[i];
next.y=now.y+dy[i];
if(isok(next.x,next.y)) continue;
if(v[next.x][next.y]) continue;
if(next.x==nx&&next.y==ny) continue;
v[next.x][next.y]=1;
next.temp+=tolower(dir[i]);
q.push(next);
}
}
return false;
}
void bfsbox()
{
memset(vis,0,sizeof(vis));
node state;
char *p;
for(int i=1;i<=n;i++)
{
p=strchr(map[i]+1,'B');
if(p)
{
state.bx=i;
state.by=(int)(p-map[i]);
}
p=strchr(map[i]+1,'S');
if(p)
{
state.px=i;
state.py=(int)(p-map[i]);
}
}
state.path="";
queue<node> q;
node now,next;
q.push(state);
while(!q.empty())
{
now=q.front();
q.pop();
if(map[now.bx][now.by]=='T')
{
cout<<now.path<<endl;
return ;
}
for(int i=0;i<4;i++)
{
next.bx=now.bx+dx[i];
next.by=now.by+dy[i];
if(isok(next.bx,next.by)) continue;
if(vis[next.bx][next.by][i]) continue;
int x=now.bx,y=now.by;
if(i==0) x=now.bx+1;
else if(i==1) x=now.bx-1;
else if(i==2) y=now.by+1;
else if(i==3) y=now.by-1;
if(isok(x,y)) continue;
if(!bfsman(now.px,now.py,x,y,now.bx,now.by)) continue;
vis[next.bx][next.by][i]=1;
next.px=now.bx;
next.py=now.by;
next.path=now.path+temp+dir[i];
q.push(next);
}
}
printf("Impossible.\n");
}
int main()
{
int kase=0;
while(scanf("%d%d",&n,&m)&&(n+m))
{
for(int i=1;i<=n;i++)
scanf("%s",map[i]+1);
printf("Maze #%d\n",++kase);
bfsbox();
cout<<endl;
}
return 0;
}