这是一个比较坑的题目,虽然很容易写,但是容易踩坑,这个坑我也踩了一个晚上,刚刚在讨论区看见后恍然大悟,就是他走三步的时候可能越过墙,然后产生结果偏小,比如样例答案计算出来为6,解决这个问题后就很容易ac了。
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<string>
#include<vector>
#include<queue>
#include<algorithm>
#include<deque>
#include<map>
#include<stdlib.h>
#include<set>
#include<iomanip>
#include<stack>
#define ll long long
#define ms(a,b) memset(a,b,sizeof(a))
#define lowbit(x) x & -x
#define fi first
#define ull unsigned long long
#define se second
#define lson (rt<<1)
#define rson (rt<<1|1)
#define endl "\n"
#define bug cout<<"----acac----"<<endl
#define IOS ios::sync_with_stdio(false), cin.tie(0),cout.tie(0)
using namespace std;
const int maxn = 1e5 + 10;
const int maxm = 1e4 + 50;
const double eps = 1e11 - 7;
const int inf = 0x3f3f3f3f;
const ll lnf = 0x3f3f3f3f3f3f3f3f;
const ll mod = 1e6 + 7;
const double pi = 3.141592653589;
int vis[55][55][4];
int a[55][55];
char s[10];
int x0, yl, xed, yed, n, m;
map<char, int>mp;
struct node
{
int x, y, f, sta;
};
queue<node>q;
bool check(int x, int y)
{
if (a[x][y] || a[x][y + 1] || a[x + 1][y] || a[x + 1][y + 1])
{
//bug;
return false;
}
else return true;
}
bool flage = false;
void bfs(int x, int y, int fa, int cnt)
{
vis[x][y][fa] = 1;
q.push({ x,y,fa,cnt });
while (!q.empty())
{
node temp = q.front();
q.pop();
if (temp.x == xed && temp.y == yed && !flage)
{
flage = true;
printf("%d\n", temp.sta);
return;
}
//bug;
for (int i = 1; i <= 3; i++)//走的距离
{
int dx = temp.x, dy = temp.y;
if (temp.f == 0)
{
dy = temp.y + i;
}
else if (temp.f == 1)
{
dx = temp.x + i;
}
else if (temp.f == 2)
{
dy = temp.y - i;
}
else
{
dx = temp.x - i;
}
if (!check(dx, dy))break;//防止穿墙
if (dx >= 1 && dy >= 1 && dx < n && dy < m && !vis[dx][dy][temp.f] && check(dx, dy))
{
vis[dx][dy][temp.f] = 1;
q.push({ dx,dy,temp.f,temp.sta + 1 });
}
}
int f = (temp.f + 1) % 4;//转向
if (!vis[temp.x][temp.y][f])vis[temp.x][temp.y][f] = 1, q.push({ temp.x,temp.y,f,temp.sta + 1 });
f = (temp.f - 1 + 4) % 4;//转向
if (!vis[temp.x][temp.y][f])vis[temp.x][temp.y][f] = 1, q.push({ temp.x,temp.y,f,temp.sta + 1 });
}
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
scanf("%d", &a[i][j]);
}
}
ms(vis, 0);
scanf("%d%d%d%d%s", &x0, &yl, &xed, &yed, s);
mp['E'] = 0, mp['S'] = 1, mp['W'] = 2, mp['N'] = 3;
bfs(x0, yl, mp[s[0]], 0);
//cout << mp[s[0]] << endl;
if (!flage)printf("-1\n");
return 0;
}