0哈希/广度优先搜索中等 LeetCode365. 水壶问题

365. 水壶问题

描述

有两个水壶,容量分别为 jug1Capacity 和 jug2Capacity 升。水的供应是无限的。确定是否有可能使用这两个壶准确得到 targetCapacity 升。

如果可以得到 targetCapacity 升水,最后请用以上水壶中的一或两个来盛放取得的 targetCapacity 升水。

你可以:

装满任意一个水壶
清空任意一个水壶
从一个水壶向另外一个水壶倒水,直到装满或者倒空

示例 1: 

输入: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
输出: true
解释:来自著名的 "Die Hard"
示例 2:

输入: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
输出: false
示例 3:

输入: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
输出: true
 

提示:

1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/water-and-jug-problem
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

分析

两个对象即便是内容相同,它的hash值也是不同的,除非子集重写hash方法。

两个瓶子只会有如下六种操作,穷尽所有可能的变化,用set集合去重,判断有没有可能等于taget。

把 X 壶的水灌进 Y 壶,直至灌满或倒空;
把 Y 壶的水灌进 X 壶,直至灌满或倒空;
把 X 壶灌满;
把 Y 壶灌满;
把 X 壶倒空;
把 Y 壶倒空。

class Solution {
    public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
        Queue<int[]> queue = new LinkedList<>();
        Set<Long> set = new HashSet<>();
        queue.offer(new int[]{0,0});
        return dfs(queue, set,jug1Capacity,jug2Capacity,targetCapacity);
    }

    public boolean dfs(Queue<int[]> queue, Set<Long> set, int ma, int mb, int t) {
        while (!queue.isEmpty()) {
            int[] arr = queue.poll();
            int a = arr[0], b = arr[1];
            if (set.contains(hash(arr))) {
                continue;
            }
            if (a == t || b == t || a+ b == t) {
                return true;
            }
            set.add(hash(arr));
            queue.offer(new int[]{ma,b});
            queue.offer(new int[]{a,mb});
            queue.offer(new int[]{0,b});
            queue.offer(new int[]{a,0});
            queue.offer(new int[]{a - Math.min(a,mb-b),b + Math.min(a,mb-b)});
            queue.offer(new int[]{a + Math.min(b,ma-a),b - Math.min(b,ma-a)});
        }
        return false;
    }

    public long hash(int[] state) {
        return (long) state[0] * 1000001 + state[1];
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值