BFS-广度优先遍历

时间:2021-04-02 17:42:28
#include <iostream>
#include <queue> using namespace std; /*
5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
0 0 4 1 6
--------------------------------
Process exited with return value 0
Press any key to continue . . .
*/ //一个坐标节点
class Node
{
public:
Node(int _x, int _y, int _flag, int _step)
{
this->x = _x;
this->y = _y;
this->flag = _flag;
this->step = _step;
}
public:
int x;
int y;
int flag;
int step;
}; int n, m;// 迷宫行、列
int beginx, beginy, endx, endy;// 入口坐标,出口坐标
int maze[20][20] = {0}, book[20][20] = {0};// 存放迷宫、标记是否访问过
int direction[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };// 方向数组
queue<Node> qmaze;// 队列 void BFS()
{
//创建一个坐标节点
Node firtnode(beginx, beginy, 0, 0); //压入队列,并设置为已经访问
qmaze.push(firtnode);
book[beginx][beginy] = 1; //队列不为空时
while(!qmaze.empty())
{
//是否找到出口
int flag = 0; //枚举四个方向
for(int i = 0; i <= 3; i++)
{
//获取下一个节点的坐标
int tx = qmaze.front().x + direction[i][0];
int ty = qmaze.front().y + direction[i][1]; //是否越界
if(tx < 0 || tx > n - 1 || ty < 0 || ty > m - 1)
{
continue;
} //是否已经访问过,是否是路
if(maze[tx][ty] == 0 && book[tx][ty] == 0)
{
book[tx][ty] = 1; Node & tempnode = qmaze.front();
Node node(tx, ty, tempnode.flag, tempnode.step += 1); qmaze.push(node);
} //如果找到,则跳出
if(tx == endx && ty == endy)
{
flag = 1;
break;
}
} //如果找到,则跳出
if(flag)
{
break;
} qmaze.pop();
}
} int main()
{
cin >> n >> m;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
cin >> maze[i][j];
cin >> beginx >> beginy >> endx >> endy; BFS(); Node & result = qmaze.front();
cout << endl << result.step; return 0;
}