bfs learning record: template/idea summary

HB Little Salted Fish Learning Record *

A little opinion

Lanqiao Cup has a lot of search questions, but there are very few bfs questions, most of which are dfs questions.
But last year, the Blue Bridge Cup took the BFS test, so I still have to study the questions well.
Since bfs searches in a loop, it cannot be traced back, so each point can only be walked once. This speeds up the search, but because each point can only be walked once, all possible paths cannot be listed. And the advantage of this is to avoid detours, and it must be the shortest path when the search results are found. So most of the shortest path questions use bfs.

My understanding of "breadth first search"

bfs, literally, is a search method that takes breadth first. When searching, it spreads around from the origin. If dfs is "searching one room and then searching another room", then bfs is "searching the cabinets of each room and then searching the tables of each room..." this kind of in-depth search. In this way, you can prioritize the search where the item may be, thereby reducing the search time.
Just as we stipulate to walk the maze in the order of "front, left and right", and when looking for the exit of the maze, it can be regarded as a search. We first record which intersections can go to at the first intersection, and then check which intersections can go to at these intersections in the prescribed order (front left and right). The intersections you have visited on the way should be marked to prevent repeated inspections. Until an intersection is viewed, it can go to the end or it is the end, and the search ends. The number of rounds we look at is the minimum number of steps to the end. In the search process, we can use an appropriate data structure to store the intersections we have passed to the destination, which is the shortest path.
In this way, the search range is large, and the path to the destination is always the shortest path. But the disadvantage is that we can't iterate out all the paths to the destination.

The general idea of ​​bfs

First of all , as mentioned in the previous fragment, we first need a two-dimensional array to mark the maze, marking the points that can be walked and obstacles (points that cannot be walked).
Second , we create a queue and add the starting point to the queue.
Next , we create a while loop, set to execute the loop when the queue is not empty.
In the loop, we first obtain the coordinates of the head node of the queue, and then we need to specify the rules of movement. For example, the "up, left, right" specified in the above example, we can use a two-dimensional array to store the coordinate changes after the movement:

int direction[4][2] = {
    
    {
    
    0,-1},{
    
    -1,0},{
    
    1,0},{
    
    0,1}}; 

The four sets of data in this array represent "up, left, right, and down" respectively, which are carried out during coordinate transformation

	int x1=x+direction[a][0];
	int y1=y+direction[a][1]; 

Then the coordinate changes can be realized. In this order, we judge the surroundings of the head node, and if we can go, we add the transformed data points to the queue. Then change the state of the new point (x1, y1) to indicate that you have been here. Prevent repeated searches.
Finally , we need to set the termination condition of the previous step to stop or return some information when the exit is found. We often make judgments after getting the head node in the loop. If the head node data is the information we want to search for, we stop the loop.

Rough template of bfs

void BFS(传入的数据)
{
    
    
	queue<int>q; //建立一个队列
	q.push(初始坐标); //把头结点(初始点)加入队列
	while(队列不为空) 
	{
    
    
		top = q.front(); //取出队首元素top
		if(队首元素top就是你要搜索的目标) 
		{
    
    
			执行一些操作
			return;
		}
		top.pop(); //将队首元素出队;
		for(按顺序寻找top的所有子节点)
		{
    
    
			把可以前往的子节点入队
			标记入队的子节点,防止下次重复入队
		}
	}
} 

bfs example

The Labyrinth of Blue Bridge Cup Xueba

Question stem
Sample input
Input Sample 1:
3 3
001
100
110
Sample output
Output Sample 1:
4
RDRD

Topic link

This question can be regarded as a classic example of bfs. The question not only asks for the shortest number of steps, but also outputs the shortest path.
So we added a string to the data structure of the queue node to store the shortest path to a certain point.
When finding the end point, output the shortest number of steps and the shortest path.
ac code:

#include<bits/stdc++.h> 
using namespace std;

struct data	//队列里的数据结构 
{
    
    
	int x;	//坐标x 
	int y;	//坐标y 
	int times;	//步数 
	string road;	//走过的路径
	data(int a,int b,int d,string c)	//构造函数 
	{
    
    
		x=a;
		y=b;
		times=d;
		road = c;	
	}	
};
queue<data>datas;	//队列用来存放点位数据 
bool maps[501][501];	//存放迷宫地图的点位 false代表可前往 true代表不可前往 
char fx[] = {
    
    'D','L','R','U'};	//方向ascii码从小到大排列 
int site[4][2] = {
    
    {
    
    0,1},{
    
    -1,0},{
    
    1,0},{
    
    0,-1}};	//下 左 右 上的坐标变化 

void bfs(int n,int m)	//传参为迷宫的大小 n为宽 m为长 
{
    
    
	datas.push(data(1,1,0,""));	//把起始点压入队列 
	maps[1][1]=true;	//标记初始点已走过 
	while(!datas.empty())	//如果队列不为空 
	{
    
    
		data now = datas.front();	//声明一个结构体变量 让now变量指向队列的头结点
		datas.pop();	//弹出头结点 
		//cout<<now.x<<" "<<now.y<<endl; 
		if(now.x==n&&now.y==m)	//如果头结点就是要找的点 就搜索结束 
		{
    
    
			cout<<now.times<<endl<<now.road<<endl;	//输出走过的路径 和步数 
			return; 
		} 
		for(int temp=0;temp<4;temp++)	//开始查找该点的四周点位 (因为只有上下左右4个走法 所以循4次 
		{
    
    
			int x1=now.x+site[temp][0];	//变换过的x坐标 
			int y1=now.y+site[temp][1]; //变换过的y坐标 
			if(maps[y1][x1])	//如果该点已经走过或者有障碍 跳过 
				continue;
			if(x1<1||y1<1||x1>n||y1>m) 	//如果坐标超出范围 就跳过此循环
				continue;
			datas.push(data(x1,y1,now.times+1,now.road+fx[temp]));	//把新点位压入队列 路径加上新选择的fx[temp] 
			maps[y1][x1] = true;	//标记已走过 
		}
	} 
}

int main()
{
    
    
	memset(maps,false,sizeof(maps));		//初始化 
	int x,y;	//接收迷宫大小
	char input;	
	cin>>y>>x;
	getchar();
	for(int y1=1;y1<=y;y1++) 	//迷宫长 
	{
    
    
		for(int x1=1;x1<=x;x1++)	//迷宫宽 
		{
    
    
			cin>>input;
			if(input=='1')
				maps[y1][x1]=true;	//如果输入是1就标记不可走
		}
		getchar();
	}
 	
 	bfs(x,y);	//bfs 迷宫长宽 与 xy坐标是相反的 所以传反着的坐标 
	
	return 0;
}

summary

In the use of bfs, the appropriate data type should be selected according to the topic data.
BFS questions often do not only allow you to output the length of the shortest path, but usually also bring something else, so you must establish a suitable structure to store the data.
The common environment of bfs is
generally used to find the shortest path of graphs without weights. The key words of the question are often "can it be reached" and "shortest path".
At present, the degree of investigation of bfs in the Blue Bridge Cup is often lower than that of dfs, but in recent years, the investigation of bfs in the Blue Bridge Cup has also increased, so it is necessary to practice well.
In short, it is better to brush more questions and accumulate more experience.

Guess you like

Origin blog.csdn.net/qq_45698148/article/details/108013725