#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};
int n,m;
char maze[1000][1000];
bool inq[1000][1000]={false};
struct node
{
int x,y;
int step;
}s,T,nodes;
bool judge(int x,int y)
{
if(x<0||x>=n||y<0||y>=m)
return false;
if(maze[x][y]=='*')
return false;
if(inq[x][y]==true)
return false;
return true;
}
int bfs() {
queue<node> q;
//s.x=x;
//s.y=y;
q.push(s);
while (!q.empty()) {
node top = q.front();
q.pop();
if (top.x == T.x && top.y == T.y)
return top.step;
for (int i = 0; i < 4; i++) {
int newx = top.x + X[i];
int newy = top.y + Y[i];
if (judge(newx, newy)) {
nodes.x = newx;
nodes.y = newy;
nodes.step = top.step + 1;
q.push(nodes);
inq[newx][newy] = true;
}
}
}
return -1;
}
int main()
{
//int n, m;
scanf("%d%d", &n, &m);
// getchar();
for (int i = 0; i < n; i++) {
getchar();
for (int j = 0; j < m; j++) {
maze[i][j] = getchar();
}
maze[i][m + 1] = '\0';
}
scanf("%d%d%d%d", &s.x, &s.y, &T.x, &T.y);
s.step = 0;
printf("%d\n", bfs());
return 0;
}
广度优先搜索例二
最新推荐文章于 2024-03-09 14:07:59 发布
1万+

被折叠的 条评论
为什么被折叠?



