12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import java.util.LinkedList;
- import java.util.Queue;
- import java.util.Scanner;
- public class Solution {
- private static int catchCow(int N, int K) {
- boolean[] used = new boolean[100001];
- Queue<Integer> queue = new LinkedList<Integer>();
- queue.offer(N);
- used[N] = true;
- int size = queue.size();
- int cnt = 0;
- while (!queue.isEmpty()) {
- Integer i = queue.poll();
- size--;
- if (i == K) return cnt;
- if (i - 1 >= 0 && !used[i - 1]) {
- queue.offer(i - 1);
- used[i - 1] = true;
- }
- if (i + 1 <= 100000 && !used[i + 1]) {
- queue.offer(i + 1);
- used[i + 1] = true;
- }
- if (i * 2 <= 100000 && !used[i * 2]) {
- queue.offer(i * 2);
- used[i * 2] = true;
- }
- if (size == 0) {
- size = queue.size();
- cnt++;
- }
- }
- return -1;
- }
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- while (scanner.hasNextInt()) {
- int N = scanner.nextInt();
- int K = scanner.nextInt();
- System.out.println(catchCow(N, K));
- }
- scanner.close();
- }
- }
|