1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| public class Solution {
public static void main(String[] args) { System.out.println(new Solution().GetMinCalculateCount(10, 100, 22, 202)); }
public long GetMinCalculateCount(long sourceX, long sourceY, long targetX, long targetY) { if (sourceX == targetX && sourceY == targetY) { return 0; } if (sourceX <= 0 || sourceY <= 0 || targetX <= 0 || targetY <= 0) { return -1; } Queue<TwoNumber> queue = new LinkedList<>(); queue.add(new TwoNumber(targetX, targetY, 0)); while (!queue.isEmpty()) { TwoNumber nums = queue.poll(); if (nums.X == sourceX && nums.Y == sourceY) { return nums.times; } else { if (nums.X % 2 == 1 && nums.Y % 2 == 1) { queue.offer(new TwoNumber(nums.X - 1, nums.Y - 1, nums.times + 1)); } else { queue.offer(new TwoNumber(nums.X - 1, nums.Y - 1, nums.times + 1)); queue.offer(new TwoNumber(nums.X / 2, nums.Y / 2, nums.times + 1)); } } } return -1; } }
class TwoNumber { long X; long Y; int times;
public TwoNumber(long X, long Y, int times) { this.X = X; this.Y = Y; this.times = times; } }
|