Solution.java 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3. import java.util.Scanner;
  4. public class Solution {
  5. private static int catchCow(int N, int K) {
  6. boolean[] used = new boolean[100001];
  7. Queue<Integer> queue = new LinkedList<Integer>();
  8. queue.offer(N);
  9. used[N] = true;
  10. int size = queue.size();
  11. int cnt = 0;
  12. while (!queue.isEmpty()) {
  13. Integer i = queue.poll();
  14. size--;
  15. if (i == K) return cnt;
  16. if (i - 1 >= 0 && !used[i - 1]) {
  17. queue.offer(i - 1);
  18. used[i - 1] = true;
  19. }
  20. if (i + 1 <= 100000 && !used[i + 1]) {
  21. queue.offer(i + 1);
  22. used[i + 1] = true;
  23. }
  24. if (i * 2 <= 100000 && !used[i * 2]) {
  25. queue.offer(i * 2);
  26. used[i * 2] = true;
  27. }
  28. if (size == 0) {
  29. size = queue.size();
  30. cnt++;
  31. }
  32. }
  33. return -1;
  34. }
  35. public static void main(String[] args) {
  36. Scanner scanner = new Scanner(System.in);
  37. while (scanner.hasNextInt()) {
  38. int N = scanner.nextInt();
  39. int K = scanner.nextInt();
  40. System.out.println(catchCow(N, K));
  41. }
  42. scanner.close();
  43. }
  44. }