import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class Test3287 {
public static final int MAX = 20000;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
int n = scan.nextInt();
int k = scan.nextInt();
System.out.println(bfs(n, k));
}
}
public static int bfs(int n, int k) {
LinkedList<Integer> queue = new LinkedList<Integer>();
boolean[] visited = new boolean[MAX + 5];
Arrays.fill(visited, false);
int[] ways = new int[MAX+5];
ways[n] = 0;
queue.add(n);
visited[n] = true;
if(n == k) {
return 0;
}
while (!queue.isEmpty()) {
int count = queue.removeFirst();
for (int i = 1; i <= 3; i++) {
int next = count;
if (i == 1) {
next--;
}
if (i == 2) {
next++;
}
if (i == 3) {
next *= 2;
}
if (next < 0 || next > MAX) {
continue;
}
if (!visited[next]) {
queue.add(next);
visited[next] = true;
ways[next] = ways[count] + 1;
}
if (next == k) {
return ways[next];
}
}
}
return 0;
}
}
这道题让我知道了,广搜与深搜的区别。
广搜求最优解,由队列(先进先出)实现。深搜是求的全部解,递归实现。