栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

试题名称 算法提高 逃跑的牛 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 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;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/777157.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号