zoukankan      html  css  js  c++  java
  • 广搜——农场主找牛

    [题目大意] 就是一个农场主为了找到自己走失的牛,要走最短的路径,只有三种走法: x->x+1;         x->x-1;         x->2x; 解释成数学问题:           给出2个数N和K(0 ≤ N ≤ 100,000,0 ≤ K ≤ 100,000),问从N经过+1或者-1或者*2能到达K的最小步数。
    [题目详解] 分3个方向BFS,找到后树的深度就是最小步数了。注意n可以比k大,这时只有-1一种办法可以从n到达k,直接减就行了.
    代码:

    import java.io.BufferedInputStream;   
    import java.util.LinkedList;   
    import java.util.Scanner;    
    public class Main {   
      
        public static final int MAX = 200000;   
      
        public static void main(String[] args) {   
      
            Scanner scan = new Scanner(new BufferedInputStream(System.in));   
            if (scan.hasNext()) {   
                int n = scan.nextInt();   
                int k = scan.nextInt();   
                System.out.println(catchTheCow(n, k));   
            }   
        }   
      
        public static int catchTheCow(int n, int k) {   
            //找到   
            if (n == k) {   
                return 0;   
            }   
            LinkedList< Integer> queue = new LinkedList();   
            boolean[] visited = new boolean[MAX + 5];   
            int[] minutes = new int[MAX + 5];   
            visited[n] = true;   
            queue.add(n);   
            while (!queue.isEmpty()) {   
                int current = queue.removeFirst();   
                for (int i = 0; i < 3; i++) {   
                    int next = current;   
                    //遍历3个方向   
                    if (i == 0) {   
                        next++;   
                    } else if (i == 1) {   
                        next--;   
                    } else if (i == 2) {   
                        next << = 1;   
                    }   
                    if (next < 0 || next > MAX) {   
                        continue;   
                    }   
                    //剪枝  保证每个数只进链表一次。
                    if (!visited[next]) {   
                        queue.add(next);   
                        visited[next] = true;   
                        minutes[next] = minutes[current] + 1;   
                    }   
                    //找到   
                    if (next == k) {   
                        return minutes[k];   
                    }   
                }   
            }   
      
            return 0;   
        }   
    }  
    
  • 相关阅读:
    Spring MVC — @RequestMapping原理讲解-1
    搭建一个SVN
    WebService远程调用技术
    Linux命令的复习总结学习
    电商-购物车总结
    单点登录系统---SSO
    JAVA的设计模式之观察者模式----结合ActiveMQ消息队列说明
    23种设计模式
    使用netty实现的tcp通讯中如何实现同步返回
    rabbitmq集群安装
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/3177161.html
Copyright © 2011-2022 走看看