Breadth First Search (BFS) C++

Breadth First Search (BFS)

Breadth-First Search (BFS) is also one of the search methods. The breadth-first search first searches for the state that is close to the initial state. In other words, it is searched in the order of starting state→all states that can be reached with only one transition→all states that can be reached with only two transitions→……

Insert picture description here
Breadth-first search uses a queue for calculation. The queue supports push and pop operations, and data elements are first in, first out. The header file is:#include <queue>

Example: The shortest path of the maze

Title description

Given a maze of size N×M. The labyrinth is composed of passages and walls, and each step can move to the adjacent four-square passages. Request the minimum number of steps required to get from the start point to the end point. Please note that this question assumes that you can move from the starting point to the end point.

Restriction conditions
N, M ≤ 100

Sample input

N=10, M=10 (The labyrinth is shown in the figure below.'#','.','S', and'G' represent walls, passages, start and end points respectively)

#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G# 

Sample output

22

Topic analysis

The breadth-first search searches in the order of nearer to farthest from the starting state, so it can be easily used to find answers to questions such as the shortest path and the fewest operations. In this problem, the state is only the coordinates of the current location, so it can be constructed pairor coded intto express the state.

In the breadth-first search, as long as the visited status is managed with a mark, the near-to-far search can be done well. In this problem, since the shortest distance is required, it might as well use d[N][M]an array to save the shortest distance. Initially initialize it with a sufficiently large constant INF, so that the position that has not yet been reached is INF, and it also serves as a marker.

Although the search will stop when it reaches the end point, if you continue until the queue is empty, you can calculate the shortest distance to each location. In addition, if d is still INF at the end of the search, it can be known that this position cannot be reached from the starting point.

Because you need to move in 4 different directions, use two arrays dx[4]and dy[4]two arrays to represent the four direction vectors. In this way, a four-direction movement traversal can be achieved through a loop.

Code

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std; 

const int INF = 100000000;
const int MAX_N = 10001;

//使用pair表示状态时,使用typedef会更方便一些 
typedef pair<int, int> P;

char maze[MAX_N][MAX_N+1];	//表示迷宫的字符串数组 
int N, M;
int sx, sy;					//起点坐标 
int gx, gy;					//终点坐标 

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

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

//求从(sx,sy)到(gx,gy)的最短距离 
//如果无法到达,则是INF 
int bfs(){
    
    
	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];
	
	//确定起始位置坐标 
	for(int i=0; i<N; i++)
		for(int j=0; j<M; j++){
    
    
			if(maze[i][j] == 'S'){
    
    
				sx = i;
				sy = j;
			}
			else if(maze[i][j] == 'G'){
    
    
				gx = i;
				gy = j;
			}
		}
	
			
	int res = bfs();
	cout << res;
	return 0;
} 

Guess you like

Origin blog.csdn.net/qq_44524918/article/details/109018248