POJ-3278 (BFS)

BFS 算法的核心:把同一级的子节点都拉入队列,之后才会去遍历下一级节点

import java.io.*;
import java.util.*;

public class POJ3278 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N = Integer.parseInt(st.nextToken());
        int K = Integer.parseInt(st.nextToken());
        if(N >= K){
            System.out.println(N - K);
        }else{
            Queue<Integer> queue = new LinkedList<Integer>();
            int maxN = 1000000;
            boolean vis[] = new boolean[maxN + 3];
            int step[]= new int[maxN + 3];
            Arrays.fill(vis, false);
            Arrays.fill(step, 0);
            vis[N] = true;
            queue.add(N);
            int cur = 0;
            int next = 0;
            while(!queue.isEmpty()){
                cur = queue.poll();
                for(int i = 1;i <= 3;i++){// x-1,x+1,2x三种方式移动
                    if(i == 1){
                        next = cur -1;
                    }else if(i == 2){
                        next = cur + 1;
                    }else if(i == 3){
                        next = cur * 2;
                    }
                    
                    if(next >=0 && next <= maxN ){
//                        System.out.println("next ==" + next);
                        if(!vis[next]){
                            step[next] = step[cur] +1;
                            queue.add(next);
                            vis[next] = true;
                        }
                        if(next == K){
                            System.out.println(step[next]);
                            return;
                        }
                    }
                }
            }
        }
    }
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值