比较有趣的一个BFS,用两个队列维护。
AC代码:
#include <bits/stdc++.h>
using namespace std;
char s[1010][1010];
bool vis[1010][1010];
int mov[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
struct node
{
int x, y, step;
};
queue<node> q1;
queue<node> q2;
int n, m, sx, sy, ex, ey;
int bfs()
{
q1.push(node{sx, sy, 0});
while (q1.size())
{
while (q1.size())
{
node temp = q1.front();
q1.pop();
q2.push(temp);
if (temp.x == ex && temp.y == ey)
return temp.step;
for (int i = 0; i < 4; i++)
{
int xx = temp.x + mov[i][0];
int yy = temp.y + mov[i][1];
if (xx < 1 || xx > n || yy < 1 || yy > m || vis[xx][yy] || s[xx][yy] == '#')
continue;
q2.push(node{xx, yy, temp.step});
q1.push(node{xx, yy, temp.step});
vis[xx][yy] = 1;
}
}
while (q2.size())
{
node temp = q2.front();
q2.pop();
for (int xx = temp.x - 2; xx <= temp.x + 2; xx++)
{
for (int yy = temp.y - 2; yy <= temp.y + 2; yy++)
{
if (xx < 1 || xx > n || yy < 1 || yy > m || vis[xx][yy] || s[xx][yy] == '#')
continue;
q1.push(node{xx, yy, temp.step + 1});
vis[xx][yy] = 1;
}
}
}
}
return -1;
}
int main()
{
cin >> n >> m >> sx >> sy >> ex >> ey;
for (int i = 1; i <= n; i++)
cin >> s[i] + 1;
cout << bfs() << endl;
return 0;
}