# Farmer chasing cattle -- the introduction to lost cattle B FS

Keywords: less

BFS algorithm

Width first search Algorithm (also known as Breadth first search )It is one of the most simple graph search algorithms, which is also the prototype of many important graph algorithms. Dijkstra Single source shortest path Algorithm and Prim minimum spanning tree The algorithm adopts the similar idea of width first search. BFS, also known as BFS, is a blind search method, which aims to systematically expand and check all nodes in the graph to find results. In other words, it does not consider the possible location of the result, and searches the entire graph thoroughly until it finds the result

Farmer chasing cattle is the basic problem of bfs. The general idea is: one step forward, one step backward, or two times the position (for example, 1 - > 2 - > 4-8 - > 16). That is to say, there are three conditions to go, namely, three judgment conditions. The following is the code, which can be understood according to the code comments

```#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
int famer[110005];           //Time spent at each location (minimum)
int cow[110005];             //Judge whether the position has passed
int n,k,y;
queue<int>q;				 //Take advantage of the first in, first out characteristics of the queue, first in, first out
int bfs()
{
q.push(n)  ;             //Put the first position in the team and deal with it
famer[n]=0;
//cout<<"y: "<<y<<" famer[y]: "<<famer[y]<<endl;
while(q.size() !=0)
{
if(y==k)break;        //If you reach the target position, jump out
y=q.front() ;         //Handle the position of the first team, which is indicated by y
q.pop() ;             //The position is already being processed. The position is out of the team
if(y+1<=100000&&cow[y+1]==0) //Judge whether the position of y+1 is less than the limit condition, and judge whether it has passed, the same below
{
q.push(y+1);           //Join this position in the team, the same below
famer[y+1]=famer[y]+1; //This position is the number of steps of the original position + 1, the same below
cow[y+1]=1;            //Mark that the position has passed, the same below
}
if(y-1>=0&&cow[y-1]==0)
{
q.push(y-1);
famer[y-1]=famer[y]+1;
cow[y-1]=1;
}
if(y*2<=100000&&cow[y*2]==0)
{
q.push(2*y);
famer[y*2]=famer[y]+1;
cow[y*2]=1;
}
//	cout<<"y: "<<y<<" famer[y]: "<<famer[y]<<endl;
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>k;
y=0;
memset(famer,0,sizeof(famer)); //Initialization
memset(cow,0,sizeof(cow));
while(q.size() !=0)            //Initialize queue
q.pop() ;
//	memset(cow,0,sizeof(cow));
bfs();
//cout<<y<<endl;
cout<<famer[y]<<endl;        //After extensive search, y==k, i.e. target location
}

}```

Posted by hthighway on Sun, 01 Dec 2019 01:29:42 -0800