poj3278 Catch That Cow(bfs java)

题目链接:http://poj.org/problem?id=3278


/**
* @param args
*            题意: FJ要抓奶牛。 开始输入N(FJ的位置)K(奶牛的位置)。
*            FJ有三种移动方法: 1、向前走一步,耗时一分钟。
*            2、向后走一步,耗时一分钟。 3、向前移动到当前位置的两倍N*2,耗时一分钟。
*            问FJ抓到奶牛的最少时间。PS:奶牛是不会动的。
*/


简单bfs  对每个点进行三种策虐的搜索 搜索每种可能


java代码

package bfs;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class poj3278 {
	static int n, k;
	static boolean vis[] = new boolean[100000 + 2];
	static int step[] = new int[100000 + 2];

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		n = scan.nextInt();
		k = scan.nextInt();
		if (n >= k) {
			System.out.println(n - k);
		} else {
			int ans=bfs();
			System.out.println(ans);
		}
	}

	private static int bfs() {
		// TODO Auto-generated method stub
		Queue<Integer> queue = new LinkedList<Integer>();
		int next=0;
		while (!queue.isEmpty()) {
			queue.clear();
		}
		queue.offer(n);
		vis[n] = true;
		step[n]=0;
		while(!queue.isEmpty()){
			int from=queue.poll();
			for(int i=0;i<3;i++){
				if(i==0){
					next=from+1;
				}
				if(i==1){
					next=from-1;
				}
				if(i==2){
					next=from*2;
				}
				if(next<0||next>100001){
					continue;
				}
				if(!vis[next]){
					step[next]=step[from]+1;
					queue.offer(next);
					vis[next]=true;
				}
				if(next==k){
					return step[k];
				}
			}
		}
		return 0;
	}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值