很难绷,四个方向来遍历的都能90
这是第一个
#include <iostream>
#include <queue>
#include <algorithm>
#include<cstring>
using namespace std;
int n, m, x1_, y1_, x2_, y2_;//起点、终点坐标
char dir;//初始方向
bool G[55][55];//图
int ans = -1;//答案
char D[4] = { 'E', 'S', 'W', 'N' }; // 方向,用于判断,服务于st
int st[4][3][2]; // 四种方向,3种方式,横纵坐标
int cir[4][2] = { {0,0},{1,0},{0,1},{1,1} };//用于判断机器人4个点
int vis[55][55];//走过就别走了
queue<int> x;
queue<int> y;
queue<char> d;//方向
queue<int> cnt;//时间
void bfs()
{
// 以左上角的点为基。
// 可以保持现状走,也可以改变方向走,无论如何都要走
// 毕竟走在路上,才能在路上,在这个意义上,方向只会增加时间。
// 初始化
x.push(x1_), y.push(y1_), cnt.push(0), d.push(dir);
vis[x1_][y1_] = 1;
while (!x.empty())
{
int nx, ny, ncnt;
char nd;
nx = x.front();
ny = y.front();
nd = d.front();
ncnt = cnt.front();
x.pop(), y.pop(), d.pop(), cnt.pop();
//找到
if (nx == x2_ && ny == y2_)
{
if (ans == -1)
ans = ncnt;
else
ans = min(ans, ncnt);
continue;
}
//难绷
for (int i = 0; i <= 3; i++) {
for (int j = 0; j < 3; j++) {
int mx= nx + st[i][j][0], my= ny + st[i][j][1], mcnt=1;
if (vis[mx][my]||mx<1||my<1||mx>=n||my>=m) {
continue;
}
//方向不一样,时间++
if (D[i] != nd) {
mcnt++;
}
mcnt += ncnt;//时间加上原来的
//判断合理
bool is_ = true;
for (int k = 0; k <= 3; k++) {
int nnx = mx + cir[k][0], nny = my+cir[k][1];
if (nnx<1 || nny<1 || nnx>n || nny>m || G[nnx][nny]) {
is_ = false;
}
}
//加入
if (is_) {
x.push(mx), y.push(my), d.push(D[i]), cnt.push(mcnt);
vis[mx][my] = 1;
}
else {
break;
}
}
}
}
}
void init()
{
memset(vis, 0, sizeof(vis));
// 'E','S','W','N'
for (int i = 0; i < 3; i++)
{
st[0][i][0] = 0;
st[0][i][1] = (i + 1);
}
for (int i = 0; i < 3; i++)
{
st[1][i][0] = (i + 1);
st[1][i][1] = 0;
}
for (int i = 0; i < 3; i++)
{
st[2][i][0] = 0;
st[2][i][1] = -(i + 1);
}
for (int i = 0; i < 3; i++)
{
st[3][i][0] = -(i + 1);
st[3][i][1] = 0;
}
}
int main()
{
init();
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> G[i][j];
}
}
cin >> x1_ >> y1_ >> x2_ >> y2_ >> dir;
bfs();
cout << ans << endl;
return 0;
}
第二个在第一个的基础上加上了
//方向不一样,时间++
if (D[i] != nd) {
mcnt++;
//东 EE,南 SS,西 WW,北 NN
if (D[i] == 'E' && nd == 'W')mcnt++;
if (D[i] == 'W' && nd == 'E')mcnt++;
if (D[i] == 'N' && nd == 'S')mcnt++;
if (D[i] == 'S' && nd == 'N')mcnt++;
}
mcnt += ncnt;//时间加上原来的