#include <iostream>
#include <queue>
using namespace std;
//定义一个点,分别表示x,y点,和已经走的步数
struct point
{
int x, y, dis;
};
//表示方向
int xx[4] = { 1,-1,0,0 },yy[4] = { 0,0,1,-1 };
int bfs(int x, int y, int a, int b, int maze[][7])
{
queue<point> myque;
point pt;
pt.x = x, pt.y = y, pt.dis = 0;
myque.push(pt);
while (!myque.empty())
{
pt = myque.front();
myque.pop();
//判断是否到达目标并返回走的步数,保证是最短路径
if (pt.x == a && pt.y == b)
{
return pt.dis;
}
//判断该点四个方向是否可以走,如果可以的话就进栈
for (int i = 0; i < 4; i++)
{
if (pt.x + xx[i] >= 0 && pt.x + xx[i] < 7 &&
pt.y + yy[i] >= 0 && pt.y + yy[i] < 7 &&
maze[pt.x + xx[i]][pt.y + yy[i]] == 0)
{
point temp;
temp.x=pt.x + xx[i];
temp.y=pt.y + yy[i];
temp.dis=pt.dis+1;
maze[pt.x][pt.y] = 1;
myque.push(temp);
}
}
}
}
int main()
{
int maze[7][7] =
{
{1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 1, 0, 1, 0, 1, 1},
{1, 0, 0, 1, 1, 1, 1},
{1, 0, 1, 0, 0, 0, 1},
{1, 0, 0, 0, 1, 0, 1},
{1, 1, 1, 1, 1, 1, 1}
};
int x, y, a, b;
cin >> x >> y >> a >> b;
cout<<bfs(x, y,a,b, maze) ;
return 0;
}
bfs广度优先迷宫,最短路径
最新推荐文章于 2023-08-15 21:13:05 发布