bfs迷宫问题模板

/*bfs一般用于求迷宫起点到终点的最短距离,原因是迷宫各个方向权值相等*/
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
#define N 50

using namespace std;

struct point {//point类型包含元素x,y坐标和当前的步数step
	int x;
	int y;
	int step;
};

point start;
point p;

queue<point> q;
int m, n;
int map[N][N] = { 0 }, vis[N][N] = { 0 };

int dx[4] = { -1,0,0,1 };//4个方向移动
int dy[4] = { 0,-1,1,0 };

int bfs()
{
	while (!q.empty())	q.pop();//清空队列
	q.push(start);//把起点加入队列
	while (!q.empty())//当队列不为空时
	{
		struct point to;
		for (int i = 0; i < 4; i++)//遍历下一步的各种情况
		{
			to.x = q.front().x + dx[i];
			to.y = q.front().y + dy[i];
			to.step = q.front().step + 1;
			if (to.x >= 1 && to.x <= m && to.y >= 1 && to.y <= n && !vis[to.x][to.y] && !map[to.x][to.y])
				q.push(to);//若下一个点符合条件就加入队列
			if (to.x == p.x && to.y == p.y)//若当前点即为终点
			{
				return to.step;//返回当前点的step
			}
		}
		q.pop();//遍历完后记得把队列的首部元素清除
	}
}

int main()
{
	while (scanf("%d%d", &m, &n) != EOF && m && n)
	{
		int ans = 0;
		for (int i = 1; i <= m; i++)//输入m行n列的地图
		{
			for (int j = 1; j <= n; j++)
			{
				scanf("%d", &map[i][j]);
			}
		}
		memset(vis, 0, sizeof(vis));//对标记数组初始化
		scanf("%d%d%d%d", &start.x, &start.y, &p.x, &p.y);//输入起点和终点
		start.step = 0;//初始化起点的步数
		vis[start.x][start.y] = 1;//标记起点为已走过
		ans = bfs();//调用bfs函数
		printf("%d\n", ans);
	}
	return 0;
}

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/yuanba_xs/article/details/54799139
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞