Breadth first search bfs

       The computer major of a certain University of Electronic Science and Technology of China has set up a flag. From now on, I will study myself. I hope that when I am a sophomore, I can enter the door of acm and pour tea and water for the big guys. Now start recording the first blog about the breadth-first algorithm.

1. Meaning

This picture is very vivid, and it shows the order of visits of each node. Wide search is a downward search layer by layer, so it is suitable for finding the shortest path problem. This picture can be regarded as going from V1 to V8, and there is no connection between Vs, which cannot be reached by one-step transfer. When searching for each step of the search, only select adjacent nodes that can be reached by one-step state transfer. .

Second, to write programs to use

Guangsou uses the queue queue to cooperate with the structure to realize.


Several methods:

First define the structure of a node:

typedef struct{
	int x;//The horizontal and vertical coordinates of the node
	int y;
}NODE;

NODE a;

Then define a queue Q with this structure type as an element

queue<NODE> Q;

1. Q.pop();//Pop up the first element in the queue, that is, the element that entered the earliest, and let him disappear.

2. Q.front();//Retrieve the value of the first element in the queue.

3. Q.empty();//Determine whether the queue is empty.

4. Q.push(a);//Push an element of the corresponding type into the queue.

3. Core code (template)

void bfs(int x,int y,int max) {

	node s,p,b;
	s.x=x;
	sy=y;
	N.push(s);//Push the starting element into the queue
	visit[x][y]=true;//After visiting the starting element, mark it to avoid repeated visits
	while(!N.empty()) {
		p = N.front();//Remove the element at the front of the queue and use it as the new pivot to find the adjacent state that can be reached by one-step transition
		N.pop();
		for(i=0; i<4; i++) {//The original title is that there are four directions to go, up, down, left and right, so here is the search for four adjacent directions
			bx=p.x+pos[i][0];//Transformation of horizontal and vertical coordinates
			b.y=p.y+pos[i][1];
			if(valid(bx,by,max)&&!visit[bx][by]) {//Determine whether the entry conditions are met, that is, it has not been visited and has not crossed the boundary
				N.push(b);
				visit[bx][by]=true;//Visit the node element, mark it
			}

		}
	}



}
Post topic: Luogu -> Proving Ground -> Breadth First Search


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324825397&siteId=291194637