Skip to content

365. Water and Jug Problem

Difficulty Topics

Description

You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs.

If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end.

Operations allowed:

  • Fill any of the jugs with water.
  • Empty any of the jugs.
  • Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty.

 

Example 1:

Input: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
Output: true
Explanation: The famous Die Hard example 

Example 2:

Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
Output: false

Example 3:

Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
Output: true

 

Constraints:

  • 1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106

Solution

water-and-jug-problem.py
class Solution:
    def canMeasureWater(self, x: int, y: int, z: int) -> bool:
        if x + y < z: return False

        queue = deque([(0, 0)])
        visited = set([(0, 0)])

        while queue:
            a, b = queue.popleft()

            if a + b == z: return True

            states = set()

            states.add((x, b))
            states.add((a, y))
            states.add((0, b))
            states.add((a, 0))
            states.add((min(x, a + b), b - (x - a) if b - (x - a) > 0 else 0))
            states.add((a - (y - b) if a - (y - b) > 0 else 0, min(y, b + a)))

            for state in states:
                if state not in visited:
                    visited.add(state)
                    queue.append(state)


        return False