Code:
#include <iostream>
#include <queue>
#include <string>
using namespace std;
struct robot
{
int x,y,second;
char rfx;
};
queue <robot> q;
int dx[]={0,0,0,1,2,3,0,0,0,-1,-2,-3};
int dy[]={1,2,3,0,0,0,-1,-2,-3,0,0,0};
// 右 上 左 下
int n,m;
int sx,sy;
int gx,gy;
char fx;
int ans=-1;
bool vis[60][60];
void bfs()
{
robot tool=q.front();
q.pop();
if(tool.x==gx&&tool.y==gy)
{
ans = tool.second;
return;
}
for(int i=0;i<12;i++)
{
int xx=tool.x+dx[i];
int yy=tool.y+dy[i];
int second=tool.second+1;
char nfx=tool.rfx;
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&vis[xx][yy]==0)
{
robot now;
now.x = xx;
now.y = yy;
if(i>=0&&i<=2) //东
{
if(nfx!='E')
now.second = second+1;
now.rfx = 'E';
}
if(i>=3&&i<=5) //北
{
if(nfx!='N')
now.second = second+1;
now.rfx = 'N';
}
if(i>=6&&i<=8) //西
{
if(nfx!='W')
now.second = second+1;
now.rfx = 'W';
}
if(i>=9&&i<=11) //南
{
if(nfx!='S')
now.second = second+1;
now.rfx = 'S';
}
vis[xx][yy] = 0;
q.push(now);
// for(int i=1;i<=n;i++)
// {
// for(int j=1;j<=m;j++)
// cout<<((i==now.x&&j==now.y)?3:vis[i][j])<<' ';
// cout<<endl;
// }
// cout<<"now.x="<<now.x<<endl;
// cout<<"now.y="<<now.y<<endl;
// cout<<"now.second="<<now.second<<endl;
// cout<<"---------------------------"<<endl;
}
}
return;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>vis[i][j];
cin>>sx>>sy;
cin>>gx>>gy;
cin>>fx;
robot first;
first.x = sx;
first.y = sy;
first.second = 0;
first.rfx = fx;
q.push(first);
bfs();
cout<<ans;
return 0;
}