试题名称 算法提高 逃跑的牛 Java(BFS)


import java.util.*;
public class Main{
    static boolean[] vis = new boolean[100005];
    static int n;
    static int k;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        k = sc.nextInt();
        bfs();
    }
    public static void bfs(){
        Queue<POS> q = new LinkedList<>();
        q.offer(new POS(n,0));
        vis[n] = true;
        while (!q.isEmpty()){
            POS now = q.poll();
            int now_position = now.position;
            int now_time = now.time;
            if(now_position == k){
                System.out.println(now_time);
                break;
            }
            int next_position = now_position+1;
            int next_time = now_time+1;
            if(check(next_position)){
                vis[next_position] = true;
                q.offer(new POS(next_position,next_time));
            }
            next_position = now_position-1;
            next_time = now_time+1;
            if(check(next_position)){
                vis[next_position] = true;
                q.offer(new POS(next_position,next_time));
            }
            next_position = now_position*2;
            next_time = now_time+1;
            if(check(next_position)){
                vis[next_position] = true;
                q.offer(new POS(next_position,next_time));
            }
        }
    }
    public static boolean check(int x){
        if(x >= 0 && x <= 100000 && vis[x] == false){
            return true;
        }
        return false;
    }
}
class POS{
    int position;
    int time;

    public POS(int position, int time) {
        this.position = position;
        this.time = time;
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Uranus^

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值