//poj 1376
//sep9
#include <iostream>
#include <queue>
using namespace std;
const int maxN=128;
int n,m,sx,sy,sdir,ex,ey;
int g[maxN][maxN],vis[maxN][maxN][4];
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
struct NODE
{
int x,y,pos,time;
};
int getDir()
{
char s[20];
scanf("%s",s);
if(!strcmp(s,"north"))
return 0;
if(!strcmp(s,"east"))
return 1;
if(!strcmp(s,"south"))
return 2;
return 3;
}
bool check(int x,int y)
{
if(x<1||x>=n||y<1||y>=m)
return false;
if(g[x][y]||g[x+1][y]||g[x][y+1]||g[x+1][y+1])
return false;
return true;
}
int bfs()
{
queue<NODE> q;
NODE a;
a.x=sx,a.y=sy,a.pos=sdir,a.time=0;
q.push(a);
vis[sx][sy][sdir]=1;
while(!q.empty()){
a=q.front(),q.pop();
int nx=a.x,ny=a.y;
if(nx==ex&&ny==ey)
return a.time;
for(int i=1;i<=3;++i){
nx+=dx[a.pos];
ny+=dy[a.pos];
if(!check(nx,ny))
break;
if(!vis[nx][ny][a.pos]){
vis[nx][ny][a.pos]=1;
NODE nxt;
nxt.x=nx,nxt.y=ny,nxt.pos=a.pos,nxt.time=a.time+1;
q.push(nxt);
}
}
for(int i=0;i<4;++i){
if(abs(a.pos-i)==2)
continue;
if(vis[a.x][a.y][i]==1)
continue;
vis[a.x][a.y][i]=1;
NODE nxt;
nxt.x=a.x,nxt.y=a.y,nxt.pos=i,nxt.time=a.time+1;
q.push(nxt);
}
}
return -1;
}
int main()
{
while(scanf("%d%d",&n,&m)==2&&(n+m)){
for(int i=1;i<=n;++i)
for(int j=1;j<=m;++j)
scanf("%d",&g[i][j]);
memset(vis,0,sizeof(vis));
scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
sdir=getDir();
if(sx==ex&&sy==ey){
printf("0\n");
continue;
}
if(!check(ex,ey)){
printf("-1\n");
continue;
}
int ans=bfs();
if(ans!=-1)
printf("%d\n",ans);
else
printf("-1\n");
}
return 0;
}
poj 1376 Robot 广搜
最新推荐文章于 2020-07-13 22:34:20 发布