The shortest path maze - breadth-first search (the BFS) - examples

BFS concept

Similar to the depth-first search, it is by some state began to explore all states reachable. But the relative depth-first search, the breadth-first search is always the first search from the initial state close to the state, that is, from near and far, first explore the most recent state to meet the conditions. Using the principle: Queue, "first in first out"; apply for the shortest, smallest and other keywords.

example
                             迷宫的最短路径                        

Given a size of N * M maze, maze passage and wall, each step can be moved in the four directions. Please find the minimum number of steps from the beginning to the end.

#include <iostream>
#include<queue>
#define MAX_N 101
#define MAX_M 101
using namespace std;
const int INF = 100000000;

//使用pair表示状态时,使用typedef会更加方便一些
typedef pair<int, int> P;
//输入+
char maze[MAX_N][MAX_M + 1];  //表示迷宫的数组
int N, M;
int tx, ty; //起点坐标
int x, y; //终点坐标

int d[MAX_N][MAX_M]; //到各个位置的最短距离的数组

//四个方向移动的向量
int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 }; //(1,0) (0,1),(-1,0),(0,-1)
//求从(sx,sy)到(gx,gy)的最短距离
//如果无法到达,则是INF
//每次计算的状态都是未尝访问过的  看哪个最先找到 终点 并且结束
//利用了队列的原理 “先进先出” 先分析先进的状态  由远及近
int bfs(int sx, int sy, int gx, int gy) {
	//用于判断是否在迷宫内
	if (sx < 0 || sx >= N || gx < 0 || gx >= M) return INF;
	queue<P> que;
	//把所有位置都初始化为INF
	for (int i = 0; i < N; ++i)
	{
		for (int j = 0; j < M; ++j) d[i][j] = INF;
	}
	//将起点加入队列,并把这一地点的距离设置为 0;
	que.push(P(sx, sy));
	d[sx][sy] = 0;
	//不断循环 直至队列的长度为0

	while (que.size())
	{
		//从队列的前端取出元素
		P p = que.front(); que.pop();
		//如果取出的状态已经是终点,则结束搜索
		if (p.first == gx && p.second == gy) break;
		//四个方向的循环
		for (int i = 0; i < 4; ++i)
		{
			//移动之后的位置记为(nx,ny)
			int nx = p.first + dx[i], ny = p.second + dy[i];
			//判断是否可以移动以及是否已经访问过了(d[nx][ny] != INF)
			if (0 <= nx && nx < N && 0 <= ny && ny < M && maze[nx][ny] != '#'  && d[nx][ny] == INF)
			{
				//可以移动的话加入到队列,并且到该位置的距离确定为到p的距离+1
				que.push(P(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;

			}


		}
	}
	return d[gx][gy];
}


int main()
{
	//输入
	cin >> N >> M;
	for (int i = 0; i < N; ++i)
	{
		for (int j = 0; j < M; ++j) {
			cin >> maze[i][j];
		}
	}
		cin >> tx >> ty >> x >> y;
		//计算起点到终点的步数
		int res = bfs(tx, ty, x, y);
		if (res != INF)
			cout << res << endl;

		else
			cout << "No" << endl;




	return 0;
}
Published 19 original articles · won praise 3 · Views 3817

Guess you like

Origin blog.csdn.net/weixin_42792088/article/details/87911533