广搜之抓住那头牛
程序员文章站
2022-06-12 09:22:11
...
单源无权最短路径,利用广度优先搜索
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <string>
#include <iostream>
#include <stack>
#include <math.h>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <map>
#include <string>
#include <stdlib.h>
#include <vector>
#include <queue>
using namespace std;
struct step
{
int x,s;
step(int xx,int ss):x(xx),s(ss){}
};
int Max=100000;
int visited[100005];
queue <step> q;
int main()
{
int N,K;
memset(visited,0,sizeof(visited));
cin >> N >> K;
q.push(step(N,0));
visited[N]=1;
while(!q.empty())
{
step now = q.front();
if(now.x==K)
{
cout <<now.s<<endl;
return 0;
}
else
{
if(now.x-1>=0&&!visited[now.x-1])
{
q.push(step(now.x-1,now.s+1));
visited[now.x-1]= 1;
}
if(now.x+1<=Max&&!visited[now.x+1])
{
q.push(step(now.x+1,now.s+1));
visited[now.x+1]= 1;
}
if(now.x*2<=Max&&!visited[now.x*2])
{
q.push(step(now.x*2,now.s+1));
visited[now.x*2]= 1;
}
}
q.pop();
}
return 0;
}