广搜——农场主找牛

[题目大意] 就是一个农场主为了找到自己走失的牛,要走最短的路径,只有三种走法: 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;   
    }   
}  
原文地址:https://www.cnblogs.com/xiaoying1245970347/p/3177161.html