LeetCode | 0365. Water and Jug Problem水壺問題【Python】

LeetCode 0365. Water and Jug Problem水壺問題【Medium】【Python】【BFS】【數學】

Problem

LeetCode

You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs.

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

Operations allowed:

  • Fill any of the jugs completely 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: (From the famous “Die Hard” example)

Input: x = 3, y = 5, z = 4
Output: True

Example 2:

Input: x = 2, y = 6, z = 5
Output: False

問題

力扣

有兩個容量分別爲 x升 和 y升 的水壺以及無限多的水。請判斷能否通過使用這兩個水壺,從而可以得到恰好 z升 的水?

如果可以,最後請用以上水壺中的一或兩個來盛放取得的 z升 水。

你允許:

  • 裝滿任意一個水壺
  • 清空任意一個水壺
  • 從一個水壺向另外一個水壺倒水,直到裝滿或者倒空

示例 1: (From the famous “Die Hard” example)

輸入: x = 3, y = 5, z = 4
輸出: True

示例 2:

輸入: x = 2, y = 6, z = 5
輸出: False

思路

解法一

BFS

每次水壺都有三個操作:加滿水、清空水、相互倒。
Python3代碼
class Solution:
    def canMeasureWater(self, x: int, y: int, z: int) -> bool:
        # solution one: BFS
        from collections import deque
        queue = deque([[0, 0]])
        visited = set([(0, 0)])

        while queue:
            cur_x, cur_y = queue.pop()
            if z in [cur_x, cur_y, cur_x + cur_y]:
                return True
            for item in [
                # x 加滿水,y 加滿水
                (x, cur_y), (cur_x, y),
                # x 清空水,y 清空水
                (0, cur_y), (cur_x, 0),
                # 把 x 壺的水灌進 y 壺,直至灌滿或倒空
                (cur_x + cur_y - y, y) if cur_x + cur_y >= y else (0, cur_x + cur_y),
                # 把 X 壺的水灌進 Y 壺,直至灌滿或倒空
                (x, cur_x + cur_y - x) if cur_x + cur_y >= x else (cur_x + cur_y, 0)]:
                if item not in visited:
                    queue.appendleft(item)  # 從隊列左邊加入元素
                    visited.add(item)
        return False
解法二

裴蜀定理

能否找到整數 a,b 使得方程 ax + by = z 有解。
有整數解時,當且僅當 z 是 a 和 b 的最大公約數 d 的倍數。
Python3代碼
class Solution:
    def canMeasureWater(self, x: int, y: int, z: int) -> bool:
        # solution two: 裴蜀定理
        import math
        if x + y < z:
            return False
        if x == z or y == z or x + y == z:
            return True
        return z % math.gcd(x, y) == 0

GitHub鏈接

Python

參考

暴力 + 數學

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章