#include<iostream>
using namespace std;
struct note
{
int x, y;//坐标
int n;//步数
};
int main(void)
{
struct note que[2501];//队列
int a[51][51] = { 0 }, book[51][51] = { 0 };//book用来记录走过的点
int next[4][2] = { {0,1},
{1,0},
{0,-1},
{-1,0} };
int n, m, startx, starty, p, q, tx, ty, flag;//flag=0代表没到终点
cin >> n >> m;//迷宫大小
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> a[i][j];
cin >> startx >> starty >> p >> q;//起点和终点
//队列初始化
int head=1, tail=1;
que[tail].x = startx;
que[tail].y = starty;
que[tail].n = 0;//走了0步
tail++;
book[startx][starty] = 1;
flag = 0;
while (head < tail)//队列不为空,循环
{
for (int k = 0; k <= 3; k++)//枚举顺时针方向上的下一步
{
//txty代表下一个点
tx = que[head].x + next[k][0];
ty = que[head].y + next[k][1];
if (tx<1 || tx>n || ty<1 || ty>m)//越界
continue;
//这个点没有障碍物且没走过
if (a[tx][ty] == 0 && book[tx][ty] == 0)
{
book[tx][ty] = 1;//走了
//插入队列
que[tail].x = tx;
que[tail].y = ty;
que[tail].n = que[head].n + 1;//head所拥有的步数+1
tail++;
}
if (tx == p && ty == q)
{
flag = 1;
break;//退出枚举
}
//如果没有到达终点
//则要扩展完所有情况才能退出枚举
//并且循环时head不会加1
}
if (flag == 1)
break;//退出while
head++;
}
cout << que[tail - 1].n;
return 0;
}
bfs(c++
最新推荐文章于 2024-08-21 18:16:36 发布