搜索专题之广度优先搜索(BFS)
什么是BFS
宽度优先搜索算法(又称广度优先搜索)是最简便的图的搜索算法之一,这一算法也是很多重要的图的算法的原型。Dijkstra单源最短路径算法和Prim最小生成树算法都采用了和宽度优先搜索类似的思想。其别名又叫BFS,属于一种盲目搜寻法,目的是系统地展开并检查图中的所有节点,以找寻结果。换句话说,它并不考虑结果的可能位置,彻底地搜索整张图,直到找到结果为止。
BFS和DFS不同,BFS是像水波一样展开进行搜索,通常借用队列储存信息。
这样介绍太抽象,上题目。
Catch That Cow
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
- Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
- Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Input
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
题意
John要去抓牛,他和牛在一个数轴上,John每步可以移动x-1或x+1或2*x,给出他和牛的位置,求他抓到牛的最短步数。
思路
这题可以看作一条有点特殊的BFS的题目,John的三种移动的方式可以看作他的三种移动方向。
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=100001;
bool vis[maxn];//标记位置是否走过
int step[maxn];//储存达到每个位置当前所用步数
queue<int> in;
int bfs(int n,int m)
{
int start,next;
in.push(n);
step[n]=0;
vis[n]=true;
while(!in.empty())
{
start=in.front();
in.pop();
for(int i=0;i<3;i++)//三种移动方式
{
if(i==0)
next=start+1;
if(i==1)
next=start-1;
if(i==2)
next=start*2;
if(next<0||next>maxn)//处理出界情况
continue;
if(!vis[next])
{
in.push(next);
step[next]=step[start]+1;
vis[next]=true;
}
if(next==m)//到达终点
return step[next];
}
}
}
int main()
{
int n,m;
while(cin>>n>>m)
{
memset(vis,false,sizeof(vis));
memset(step,0,sizeof(step));
while(!in.empty())
in.pop();
cout<<bfs(n,m)<<endl;
}
return 0;
}
/