农夫要抓奶牛。 已知N(农夫的位置)K(奶牛的位置)(在一条直线上)。
农夫有三种移动方法(奶牛不会动):
1、向前走一步,耗时一分钟。
2、向后走一步,耗时一分钟。
3、向前移动到当前位置的两倍N*2,耗时一分钟。
求农夫抓到奶牛的最少时间。
广度优先搜索:
int bfs(int n,int k){
bool s[2*k+1];
for(int i=0;i<k+1;i++){
s[i]=false;
}
int queue[100][2];
int head=0,rear=0;
queue[rear][0]=n;
queue[rear++][1]=0;
s[n]=true;
int count=0;
while(rear!=head){
int pos=queue[head][0];
int count=queue[head++][1];
if(pos==k){
return count;
}else{
for(int i=0;i<3;++i){
int temp;
if(i==0){
temp=pos+1;
}else if(i==1){
temp=pos-1;
}else{
temp=pos*2;
}
if(!(temp>