这个就直接上一道例题了,
题目链接:点击打开链接
题意:这道题目就是给你一个起点和一个终点,然后让你找最短的时间到达那个点,用的是深搜,但是深搜我不怎么会,看完这个题目我才知道 深搜就是用的队列的先进先出的性质,来一层一层的搜索,如果要全部输出,就要等到队列为空时候(感觉这里说错了,这个队列是永远不会是空的,所以还是有一个判断条件和,不然就会无限制的循环下去),如果是只输出一组,判断第一组的时候直接return 就可以了,另外还要标记那个一个被搜索过了(这一点很重要),这个比深搜简单!!!!!!!
代码:
#include<math.h>
#include<string.h>
#include<string>
#include<queue>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<cmath>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<cmath>
//#define maxn 100000
using namespace std;
const int maxn=100005;
int n,m;
int visit[maxn+10];
struct node
{
int x;
int step;
};
定义一个结构体
int bfs()
{
memset(visit,0,sizeof(visit));
queue<node>q;
node now,next;
结构体变量
now.x=n;
now.step=0;
q.push(now);这个很重要
visit[now.x]=1;
while(!q.empty())
{
now=q.front();
q.pop();
for(int i=0; i<3; i++)
{
if(i==0)
next.x=now.x-1;
else if(i==1)
next.x=now.x+1;
else
next.x=now.x*2;
next.step=now.step+1;先输入再输出
if(now.x==m)
return now.step;
if(next.x>=0&&next.x<=maxn&&!visit[next.x])
{
q.push(next);
visit[next.x]=1;
}
}
}
return 0;
}
深搜
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==m)
printf("0\n");
else
{
int i,j;
int g=bfs();
printf("%d\n",g);
}
}
return 0;
}